concise java Solution using StringBuilder


  • 0
    class Solution {
        public int compress(char[] chars) {
            if(chars == null || chars.length == 0) return 0;
            
            int curr_cnt = 1;
            StringBuilder s = new StringBuilder("");
            
            for(int i=1;i<chars.length;++i){
                if(chars[i] == chars[i-1]) ++curr_cnt;
                else{
                    if(curr_cnt > 1) s.append(chars[i-1] + String.valueOf(curr_cnt));
                    else s.append(chars[i-1]);
                    curr_cnt = 1;
                }
            }
            
            if(curr_cnt > 1) s.append(chars[chars.length-1] + String.valueOf(curr_cnt));
            else s.append(chars[chars.length-1]);
                                  
            int len = s.length();        
            if(len > chars.length) return chars.length;        
            for(int i=0;i<len;++i) chars[i] = s.charAt(i);        
            return len;
        }
    }
    

Log in to reply
 

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