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

Algorithm

[Algorithm/Java][ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋ฌธ์ž์—ด ์••์ถ•

๋ฐ˜์‘ํ˜•

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋ฌธ์ž์—ด ์••์ถ•

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

๋ฌธ์ œ ์ ‘๊ทผ

๊ธด ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ ์ค„์ด๊ธฐ์œ„ํ•ด์„œ ๋ฌธ์ž์—ด์„ n๊ฐœ ๋‹จ์œ„๋กœ ์ž˜๋ผ์„œ ๊ฐ™์€ ๋ฌธ์ž์—ด str์ด n๋ฒˆ ๋ฐ˜๋ณต๋˜๋ฉด nstr๋กœ ํ‘œํ˜„ํ•˜์—ฌ ์••์ถ•ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.
compressString ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์„œ ์••์ถ•ํ•˜๋ ค๋Š” ๋ฌธ์ž์—ด s์™€ ์ž๋ฅด๋ ค๋Š” ๋ฌธ์ž์—ด์˜ ๊ธธ์ด len์„ ๋ฐ›์•„์„œ s๋ฅผ len๋‹จ์œ„๋กœ ์ž˜๋ผ ์••์ถ•ํ•œ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ํ•˜์˜€๋‹ค.

Code

class Solution {
    public int solution(String s) {
        int answer = s.length();
        for(int i = 1; i<=s.length()/2; i++){
            answer = Math.min(answer, compressString(s,i));
        }
        return answer;
    }
    /**
    * ๋ฌธ์ž์—ด s๋ฅผ len๊ธธ์ด๋งŒํผ ์ž˜๋ผ์„œ ์••์ถ•ํ•œ ๋’ค, ์••์ถ•ํ•œ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
    */
    public int compressString(String s, int len){
        StringBuilder sb = new StringBuilder();
        String prev = s.substring(0,len);
        int cnt = 1;
        int i;
        for(i = len; i<s.length(); i+=len){
            String cur;
            if(i+len>s.length()){
                cur = s.substring(i,s.length());
            } else {
                cur = s.substring(i,i+len);
            }

            if(prev.equals(cur)){
                cnt++;
            }
            else{
                if(cnt == 1){
                    sb.append(prev);
                } else {
                    sb.append(cnt).append(prev);
                    cnt = 1;
                }
            }
            prev = cur;
        }
        // ๋งˆ์ง€๋ง‰์€ ๊ฒ€์‚ฌ๋ฅผ ์•ˆํ•˜๋‹ˆ๊นŒ ํ•œ๋ฒˆ ๋” ๊ฒ€์‚ฌํ–ˆ๋‹ค.
        if(cnt != 1){
            sb.append(cnt).append(prev);
        } else {
            sb.append(prev);
        }

        return sb.toString().length();
    }
}

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

๋ง‰ํ˜”๋˜ ๋ถ€๋ถ„์€ ๋งŒ์•ฝ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ 11์ธ ๋ฌธ์ž์—ด์„ ๋”ฑ ๋–จ์–ด์ง€์ง€์•Š๋Š” 3์ด๋‚˜ 4๋กœ ์ž˜๋ž์„ ๋•Œ, len๋ณด๋‹ค ์ž‘์€ ๊ธธ์ด์˜ ๋ฌธ์ž์—ด์ด ๋‚จ์•˜์„ ๋•Œ ์ด๊ฒƒ์„ ์ฒ˜๋ฆฌํ•˜์ง€ ๋ชปํ•ด์„œ ํ‹€๋ ธ๋Š”๋ฐ ์˜์™ธ๋กœ ์‰ฝ๊ฒŒ ์ƒ๊ฐํ•˜๊ณ  ์•„๋ž˜ ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ํ•˜๋‹ˆ๊นŒ ํ’€๋ ธ๋‹ค. ๋„ˆ๋ฌด ์–ด๋ ต๊ฒŒ ์ƒ๊ฐํ•˜๊ณ  ์ด์ƒํ•˜๊ฒŒ ์ ‘๊ทผํ–ˆ๋˜ ๊ฒƒ ๊ฐ™๋‹ค.

if(i+len>s.length()){
cur = s.substring(i,s.length());
} else {
cur = s.substring(i,i+len);
}

๋ฐ˜์‘ํ˜•