Java O(n), two pointers and a counter


  • 5
    Z
    public int compress(char[] chars) {        
            int start = 0;
            for(int end = 0, count = 0; end < chars.length; end++) {
                count++;
                if(end == chars.length-1 || chars[end] != chars[end + 1] ) {
                    //We have found a difference or we are at the end of array
                    chars[start] = chars[end]; // Update the character at start pointer
                    start++;
                    if(count != 1) {
                        // Copy over the character count to the array
                        char[] arr = String.valueOf(count).toCharArray();
                        for(int i=0;i<arr.length;i++, start++)
                            chars[start] = arr[i];
                    }
                    // Reset the counter
                    count = 0;
                }
            }
            return start;
        }
    

  • 0
    F

    Similar idea

    class Solution {
        public int compress(char[] chars) {
            int count = 1;
            int j = 0;
            for (int i = 0; i < chars.length; i++) {
                if (i != chars.length - 1 && chars[i] == chars[i + 1]) {
                    count++;
                } else {
                    chars[j++] = chars[i];
                    if (count != 1) {
                        String num = count+ "";
                        for (int k = 0; k < num.length(); k++) {
                            chars[j++] = num.charAt(k);
                        }
                    }
                    count = 1;
                }
            }
            return j;
        }
    }
    

  • 0
    T

    Is it still correct if the input is ["a", "b", "a", "b"] ?


Log in to reply
 

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