๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

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

๋ฐ˜์‘ํ˜•

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

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

๋ฌธ์ œ์ ‘๊ทผ

๋ฌธ์ž์—ด์—์„œ n๋ฒˆ์งธ ๋ฌธ์ž๋กœ ๋จผ์ € ์ •๋ ฌํ•˜๊ณ  ๋‚˜๋จธ์ง€๋Š” ์‚ฌ์ „์ˆœ์œผ๋กœ ์ •๋ ฌ์„ ํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๊ธฐ์กด์— sort ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ๋Š” ์ •๋ ฌ์„ ํ•  ์ˆ˜๊ฐ€ ์—†์–ด์„œ Comparator์— compareํ•จ์ˆ˜๋ฅผ ์ง์ ‘ ์ปค์Šคํ…€ํ•ด์„œ Arrays.sort๋ฅผ ์‚ฌ์šฉํ•˜์˜€๋‹ค.

Code

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 s1.compareTo(s2);
                } else {
                    return s1.charAt(n) - s2.charAt(n);
                }
            }
        });
        return strings;
    }
}

์–ด๋ ค์› ๋˜ ์ / ๋ฐฐ์šด ์ 

Arrays.sort์—์„œ ๋‘ ๋ฒˆ์งธ ๋งค๊ฐœ๋ณ€์ˆ˜์—์„œ Comparator๋ฅผ ์ƒˆ๋กœ ๋งŒ๋“ค์–ด์„œ compareํ•จ์ˆ˜๋ฅผ ์˜ค๋ฒ„๋ผ์ด๋“œ ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ปค์Šคํ…€ํ•ด์„œ ์ •๋ ฌํ•˜๋Š” ๋ฐฉ์‹์„ ์‚ฌ์šฉํ–ˆ๋‹ค. ์ด์™€ ๊ฐ™์€ ๋ฐฉ๋ฒ•์œผ๋กœ ๋ฐฐ์—ด ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ์ปฌ๋ ‰์…˜๋“ค์„ ์ •๋ ฌํ•  ๋•Œ๋„ ๋™์ผํ•œ ๋ฐฉ์‹์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

๋ฐ˜์‘ํ˜•