[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] Lv1. ๋ฌธ์ž์—ด ๋‚ด ๋งˆ์Œ๋Œ€๋กœ ์ •๋ ฌํ•˜๊ธฐ

2023. 3. 7. 09:25ใ†์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค_2023

728x90

 

๋ฌธ์ œ ์„ค๋ช…

๋ฌธ์ž์—ด๋กœ ๊ตฌ์„ฑ๋œ ๋ฆฌ์ŠคํŠธ strings์™€, ์ •์ˆ˜ n์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ๊ฐ ๋ฌธ์ž์—ด์˜ ์ธ๋ฑ์Šค n๋ฒˆ์งธ ๊ธ€์ž๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•˜๋ ค ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด strings๊ฐ€ ["sun", "bed", "car"]์ด๊ณ  n์ด 1์ด๋ฉด ๊ฐ ๋‹จ์–ด์˜ ์ธ๋ฑ์Šค 1์˜ ๋ฌธ์ž "u", "e", "a"๋กœ strings๋ฅผ ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค.

์ œํ•œ ์กฐ๊ฑด
  • strings๋Š” ๊ธธ์ด 1 ์ด์ƒ, 50์ดํ•˜์ธ ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.
  • strings์˜ ์›์†Œ๋Š” ์†Œ๋ฌธ์ž ์•ŒํŒŒ๋ฒณ์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค.
  • strings์˜ ์›์†Œ๋Š” ๊ธธ์ด 1 ์ด์ƒ, 100์ดํ•˜์ธ ๋ฌธ์ž์—ด์ž…๋‹ˆ๋‹ค.
  • ๋ชจ๋“  strings์˜ ์›์†Œ์˜ ๊ธธ์ด๋Š” n๋ณด๋‹ค ํฝ๋‹ˆ๋‹ค.
  • ์ธ๋ฑ์Šค 1์˜ ๋ฌธ์ž๊ฐ€ ๊ฐ™์€ ๋ฌธ์ž์—ด์ด ์—ฌ๋Ÿฟ ์ผ ๊ฒฝ์šฐ, ์‚ฌ์ „์ˆœ์œผ๋กœ ์•ž์„  ๋ฌธ์ž์—ด์ด ์•ž์ชฝ์— ์œ„์น˜ํ•ฉ๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ
strings                                                                               n            return
["sun", "bed", "car"] 1 ["car", "bed", "sun"]
["abce", "abcd", "cdx"] 2 ["abcd", "abce", "cdx"]
์ž…์ถœ๋ ฅ ์˜ˆ ์„ค๋ช…

์ž…์ถœ๋ ฅ ์˜ˆ 1
"sun", "bed", "car"์˜ 1๋ฒˆ์งธ ์ธ๋ฑ์Šค ๊ฐ’์€ ๊ฐ๊ฐ "u", "e", "a" ์ž…๋‹ˆ๋‹ค. ์ด๋ฅผ ๊ธฐ์ค€์œผ๋กœ strings๋ฅผ ์ •๋ ฌํ•˜๋ฉด ["car", "bed", "sun"] ์ž…๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ 2
"abce"์™€ "abcd", "cdx"์˜ 2๋ฒˆ์งธ ์ธ๋ฑ์Šค ๊ฐ’์€ "c", "c", "x"์ž…๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์ •๋ ฌ ํ›„์—๋Š” "cdx"๊ฐ€ ๊ฐ€์žฅ ๋’ค์— ์œ„์น˜ํ•ฉ๋‹ˆ๋‹ค. "abce"์™€ "abcd"๋Š” ์‚ฌ์ „์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜๋ฉด "abcd"๊ฐ€ ์šฐ์„ ํ•˜๋ฏ€๋กœ, ๋‹ต์€ ["abcd", "abce", "cdx"] ์ž…๋‹ˆ๋‹ค.

 

 

 

๋‚˜์˜ ํ’€์ด

public String[] solution(String[] strings, int n) {
   String[] answer = new String[strings.length];
   ArrayList<String> arrayList = new ArrayList<>();
   for (int i = 0; i < strings.length; i++)
   {
      arrayList.add(strings[i].charAt(n) + strings[i]);
   }
   
   Collections.sort(arrayList);
   
   for (int i = 0; i < answer.length; i++)
   {
      answer[i] = arrayList.get(i)
            .substring(1, arrayList.get(i).length());
   }
   
   return answer;
}

์ฒ˜์Œ์—๋Š” ์ด ๋ฌธ์ œ๋ฅผ ์–ด๋–ป๊ฒŒ ํ’€๊นŒ..ํ•˜๋‹ค๊ฐ€ Map์— key์— ์ธ๋ฑ์Šค์— ํ•ด๋‹นํ•˜๋Š” ๋ฌธ์ž๋ฅผ ๋„ฃ์–ด์„œ ์ •๋ ฌํ•˜๋ ค๊ณ  ํ–ˆ๋Š”๋ฐ..!

๊ฐ™์€ ์ธ๋ฑ์Šค๊ฐ€ ์žˆ๋‹ค๋Š”๊ฑธ ์ƒ๊ฐํ•˜๊ณ  ๋ณด๋‹ˆ๊นŒ Map์œผ๋กœ ํ’€๋ฉด ๋” ๊ท€์ฐฎ์•„์ง€๋Š” ๋Š๋‚Œ์— Arraylist๋ฅผ ์ƒ๊ฐํ–ˆ๋‹ค. 

๋จผ์ € ์ธ๋ฑ์Šค ๊ฐ’์— ํ•ด๋‹นํ•˜๋Š” ๋ฌธ์ž๋กœ ์ •๋ ฌํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ด ๊ฐ’์„ ๊บผ๋‚ด์„œ ๋งจ ์•ž์— ์ถ”๊ฐ€ํ•œ ๋ฌธ์ž์—ด์„ Arraylist์— ์ €์žฅํ•˜๊ณ  Collections ์˜ sort๋ฅผ ํ•ด์„œ ์ •๋ ฌํ•ด์คฌ๋‹ค. 

 

๊ทธ๋ฆฌ๊ณ  ์ด์ œ ๋ฌธ์ž์—ด ๋งจ ์•ž์— ์žˆ๋Š” ๊ฐ’๋งŒ ๋นผ๊ณ  answer ๋ฐฐ์—ด์— ๋„ฃ์–ด์ฃผ๋ฉด ์›ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค. 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90