Java easy to understand solution


  • 0
        public int compress(char[] chars) {
            int count = 0;
            int index = 0;
            for (int i = 0; i <= chars.length; i++) {
                if (i == 0 || i < chars.length && chars[i] == chars[i - 1]) {
                    count++;
                }
                else {
                    chars[index] = chars[i - 1];
                    index++;
                    if (count != 1) {
                        char[] countArr = String.valueOf(count).toCharArray();
                        for (int j = 0; j < countArr.length; j++) {
                            chars[index] = countArr[j];
                            index++;
                        }
                    }
                    count = 1;
                }
            }
            return index;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.