본문 바로가기

Coding Test

Leetcode 3163 String Compression III (Java)

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

class Solution {
    public String compressedString(String word) {
        
        Integer cnt=1;
        char ch=word.charAt(0);
        String comp="";

        if(word.length()==1){
            comp+=cnt.toString()+ch;
        }

        for(int i=1;i<word.length();i++){

            if(ch!=word.charAt(i) || cnt==9){
                comp+=cnt.toString()+ch;
                cnt=1;
                ch=word.charAt(i);
            }else{
                cnt++;
            }

            if(i==word.length()-1){
                comp+=cnt.toString()+ch;
            }
        }



        return comp;
    }
}

1. 문제

소문자로만 이루어진 문자열 하나가 주어진다. 해당 문자열을 다음의 규칙에 맞추어 압축하려 한다.

  • 같은 문자가 최대 9번 반복되는 문자를 하나로 압축한다.
  • 해당 문자의 앞에 그 길이를 추가한다.

이 때 압축 결과를 출력하라.

2. 풀이

단순  문자열 풀이 문제였다.

        Integer cnt=1;
        char ch=word.charAt(0);
        String comp="";

        if(word.length()==1){
            comp+=cnt.toString()+ch;
        }

우선 맨 앞자를 저장하고, 1을 센다. 문자열의 길이가 하나라면 다음의 반복문을 돌 수 없으므로 해당 문자를 압축한다.

        for(int i=1;i<word.length();i++){

            if(ch!=word.charAt(i) || cnt==9){
                comp+=cnt.toString()+ch;
                cnt=1;
                ch=word.charAt(i);
            }else{
                cnt++;
            }

            if(i==word.length()-1){
                comp+=cnt.toString()+ch;
            }
        }

그 이후 문자를 하나씩 세면서 같은 문자라면 개수를 추가하고, 다른 문자이거나 9개에 도달하였다면 이전까지의 문자를 압축, 현재 문자부터 다시 세어준다. 반복문의 끝에 다다랐다면 끝에서부터 아직 압축하지 않은 문자를 압축해준다.

 해당 결과를 리턴하면 문제를 해결할 수 있다.