Deep_Dev
article thumbnail

 

 

 

https://school.programmers.co.kr/learn/courses/30/lessons/12915

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 

 

 

1๋ฒˆ ํ’€์ด

import java.util.*;
class Solution {
    public String[] solution(String[] strings, int n) {
        String[] answer = new String[strings.length];

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

 

์ฒ˜์Œ์—” ์ด๋ ‡๊ฒŒ ํ’€์—ˆ์—ˆ๋Š”๋ฐ..๊ทธ๋Ÿฌ๋‹ˆ๊นŒ ์–ด์ฐจํ”ผ ๋น„๊ต๋ฌธ์ž๊ฐ€ ๊ฐ™์„ ๊ฒฝ์šฐ ์ „์ฒด ๋ฌธ์ž์—ด์„ ๊ธฐ์ค€์œผ๋กœ ๋น„๊ตํ•˜๋‹ˆ๊นŒ, 

๋น„๊ต๋ฌธ์ž๋ฅผ ๋งจ ์•ž์— ๋‘๊ณ  ๋ฌธ์ž์—ด์„ ๊ทธ๋Œ€๋กœ ํ•ฉ์ณ์ฃผ๊ณ  ์ •๋ ฌ(sort)๋ฅผ ํ•˜๊ณ 

์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ์—์„œ ๋งจ ์ฒ˜์Œ ๋ฌธ์ž๋งŒ ๋นผ๊ณ  ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š”๊ฒƒ์ด๋‹ค.

 

๊ทผ๋ฐ ์ด๋ ‡๊ฒŒ ๋ง๊ณ  compare๋ฅผ ์“ฐ๋Š” ๋ฐฉ๋ฒ•์„ ์ฐพ์•„๋ณด์•˜๋‹ค.

 

 

2๋ฒˆ ํ’€์ด

import java.util.*;

class Solution {
  public String[] solution(String[] strings, int n) {
      Arrays.sort(strings, new Comparator<String>(){
          @Override
          public int compare(String s1, String s2){
              if(s1.charAt(n) > s2.charAt(n)) return 1;
              else if(s1.charAt(n) == s2.charAt(n)) return s1.compareTo(s2);
              else if(s1.charAt(n) < s2.charAt(n)) return -1;
              else return 0;
          }
      });
      return strings;
  }
}

 

์ค‘๊ฐ„ ์ฝ”๋“œ๋ฅผ ๋ณด๋ฉด 

return 1 : ๋‘ ์š”์†Œ๋ฅผ ์„œ๋กœ ๋ฐ”๊ฟ”์•ผ ํ•œ๋‹ค๋Š”๊ฒƒ์„ ๋‚˜ํƒ€๋‚ธ๋‹ค. ์ฆ‰, ์ฒซ๋ฒˆ์งธ ์š”์†Œ๊ฐ€ ๋‘๋ฒˆ์จฐ ์š”์†Œ๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ์— ์‚ฌ์šฉ๋œ๋‹ค. ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๋‘ ์š”์†Œ๊ฐ€ ์„œ๋กœ ๋ฐ”๋€Œ์–ด์„œ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋œ๋‹ค.

return -1 : ๋‘ ์š”์†Œ์˜ ์ˆœ์„œ๋ฅผ ๋ณ€๊ฒฝํ•  ํ•„์š”๊ฐ€ ์—†๋Š” ๊ฒƒ์ด๋‹ค. ์ฆ‰, ์ฒซ๋ฒˆ์งธ ์š”์†Œ๊ฐ€ ๋‘๋ฒˆ์งธ ์š”์†Œ๋ณด๋‹ค ์ž‘์€ ๊ฒฝ์šฐ์— ์‚ฌ์šฉ๋œ๋‹ค. ์ด ๊ฒฝ์šฐ ๋‘ ์š”์†Œ์˜ ์ˆœ์„œ๊ฐ€ ์ด๋ฏธ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์ •๋ ฌ๋˜์–ด ์žˆ๋‹ค๋Š” ์˜๋ฏธ์ด๋‹ค.