Step-by-Step

[Java] Daily LeetCode Challenge 443. String Compression 본문

언어/JAVA

[Java] Daily LeetCode Challenge 443. String Compression

희주(KHJ) 2023. 3. 2. 18:03

https://leetcode.com/problems/string-compression/

 

String Compression - LeetCode

Can you solve this real interview question? String Compression - Given an array of characters chars, compress it using the following algorithm: Begin with an empty string s. For each group of consecutive repeating characters in chars: * If the group's leng

leetcode.com

 

 

알파벳1 - 연속된 수 (1제외) - 알파벳2 - 연속된 수 - ... 로 나타내는 작업이다

return이 의미가 없긴 한데, input값으로 들어오는 배열을 위의 방식으로 값을 바꿔주면 된다

주의할 점은 같은 알파벳이 뒤에 또 나올 수 있다는 점 !

 

[코드]

class Solution {
    public int compress(char[] chars) {
        int cnt = 0, idx = 0;
        char bef = chars[0];

        for(char ch : chars){
            if(ch != bef){
                chars[idx++] = bef;
                
                if(cnt != 1){
                    String cntS = cnt+"";
                    for(int i=0; i<cntS.length(); i++)
                        chars[idx++] = cntS.charAt(i);
                }

                cnt = 0;
                bef = ch;
            }
            cnt++;
        }

        chars[idx++] = bef;
                
        if(cnt != 1){
            String cntS = cnt+"";
            for(int i=0; i<cntS.length(); i++)
                chars[idx++] = cntS.charAt(i);
        }

        return idx;
    }
}
Comments