Clean Java Code


  • 0
    class Solution {
        public int compress(char[] chars) {
            if (chars == null || chars.length == 0) {
                return 0;
            }
            int idx = 0;
            int cnt = 0;
            char curr = 'a';
            for (char c : chars) {
                if (c == curr) {
                    cnt++;
                } else {
                    // append previous 
                    if (cnt != 0) {
                        chars[idx++] = curr;
                        if (cnt != 1) {
                            char[] temp = String.valueOf(cnt).toCharArray();
                            for (char t : temp) {
                                chars[idx++] = t;
                            }
                        }
                    }
                    // update
                    curr = c;
                    cnt = 1;
                }
            }
            chars[idx++] = curr;
            if (cnt != 1) {
                char[] temp = String.valueOf(cnt).toCharArray();
                for (char t : temp) {
                    chars[idx++] = t;
                }
            }
            return idx;
        }
    }
    

Log in to reply
 

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