알고리즘

2024 11 04 3163. String Compression III

물빠진떡 2024. 11. 4. 16:04

문제

Given a string word, compress it using the following algorithm:

Begin with an empty string comp. While word is not empty, use the following operation:
Remove a maximum length prefix of word made of a single character c repeating at most 9 times.
Append the length of the prefix followed by c to comp.
Return the string comp.

요약

연속된 문자가 몇개있는지 세되 9개 씩만

풀이

어렵진않다 우선 첫글자를 저장해두고 다음 문자가 같은지 비교후 다르거나 9를 넘는다면 sb에 push해주고 아니면 count ++을 해준다.

코드

class Solution {
    public String compressedString(String word) {
        StringBuilder sb = new StringBuilder();
        char c = word.charAt(0);
        int count = 1;
        for (int i = 1; i < word.length(); i ++) {
            if (c != word.charAt(i) || count == 9) {
                sb.append(count);
                sb.append(c);
                c = word.charAt(i);
                count = 1;
                continue;
            }
            count ++;
        }
        sb.append(count);
        sb.append(c);
        return sb.toString();
    }
}

풀이 시간

5분

체감 난이도

easy