LeetCode/string/StringCompression.java
// modifying the input array, return the new length of the array.
modifying the input array, return the new length of the array.
modifying the input array return the new length of the array .
public int compress(char[] chars) {
        if (chars.length < 2) {
            return chars.length;
        }
        int count = 1;
        for (int i = 0; i < chars.length; i++) {
            if (i < chars.length - 1 && chars[i] == chars[i + 1]) {
                count++;
            } else {
                if (count > 2) {
                    for (int j = i; j < chars.length - 1; j++) {
                        chars[j] = chars[j + 1];
                    }
                }
                if (count > 1) {
                    chars[i] = (char) (count + '0');
                }
                count = 1;
            }
        }
        System.out.println(chars);
        return chars.length;
    }
public int compress ( char [ ] chars ) { if ( chars . length < 2 ) { return chars . length ; } int count = 1 ; for ( int i = 0 ; i < chars . length ; i ++ ) { if ( i < chars . length - 1 && chars [ i ] == chars [ i + 1 ] ) { count ++ ; } else { if ( count > 2 ) { for ( int j = i ; j < chars . length - 1 ; j ++ ) { chars [ j ] = chars [ j + 1 ] ; } } if ( count > 1 ) { chars [ i ] = ( char ) ( count + '0' ) ; } count = 1 ; } } System . out . println ( chars ) ; return chars . length ; }
modifying the input array, return the new length of the array.
modifying the input array return the new length of the array .
// StringBuilder sb = new StringBuilder(); // count & replace // sb.append(chars[i]); // sb.append(count); // chars = sb.toString().toCharArray();