Skip to content

Latest commit

 

History

History
54 lines (38 loc) · 859 Bytes

File metadata and controls

54 lines (38 loc) · 859 Bytes

String Compression

Problem Link

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


Pattern

  • String

Approach

Use write pointer to compress in-place. Count consecutive characters and update chars array.


Time Complexity

O(n)

Space Complexity

O(1)


Java Solution

class Solution {
    public int compress(char[] chars) {
        int write = 0;
        for (int i = 0; i < chars.length; ) {
            char c = chars[i];
            int count = 0;
            while (i < chars.length && chars[i] == c) {
                count++;
                i++;
            }
            chars[write++] = c;
            if (count > 1) {
                for (char d : String.valueOf(count).toCharArray()) {
                    chars[write++] = d;
                }
            }
        }
        return write;
    }
}