443. String Compression

;  |     Back to Homepage   |     Back to Code List


public int compress(char[] chars) {
    int indexRes = 0, i = 0;
    while (i < chars.length) {
        char cur = chars[i];
        int count = 0;

        while (i < chars.length && chars[i] == cur) {
            count++;
            i++;
        }

        chars[indexRes++] = cur;
        if (count != 1) {
            for (char c : String.valueOf(count).toCharArray()) {
                chars[indexRes++] = c;
            }
        }
    }

    return indexRes;
}