[Array / String, Medium] String Compression

송재호·2025년 3월 9일
0

https://leetcode.com/problems/string-compression/description/?envType=study-plan-v2&envId=leetcode-75

추가 공간을 사용하면 안되고 원본 배열을 활용해야 한다.

순회하면서 start character와 같은것이 찾아지는 만큼 count++, i++ 해 주고,
별도의 new index를 만들어 문자 + 카운트 길이만큼 집어넣어준다.

new Index는 배열에서 변경된 포인트에 대한 인덱스이며
결과적으로 이것을 이용해 새로운 배열의 길이를 알 수 있다. (원래 index +1이지만 모두 index++ 연산을 하고 있으므로 별도처리 필요없음)

class Solution {
    public int compress(char[] chars) {
        int n = chars.length;
        int newIndex = 0;

        for (int i=0; i<n;) {
            char c = chars[i];
            int count = 0;

            while (i < n && chars[i] == c) {
                count++;
                i++;
            }

            chars[newIndex++] = c;

            if (count > 1) {
                for (char digit : Integer.toString(count).toCharArray()) {
                    chars[newIndex++] = digit;
                }
            }
        }

        return newIndex;
    }
}
profile
식지 않는 감자

0개의 댓글