Just 2 pointers,


  • 0
    G
    public int compress(char[] chars) {
           if(chars==null || chars.length == 0)
           {
               return 0;
           }
           
           int start = 0;
           int j=0; 
           for(int i = 1; i<=chars.length;i++)
           {
               if(i==chars.length || chars[i] != chars[i-1])
               {
                   //compress last segment
                   chars[j++] = chars[i-1];
                   int len = i - start;
                   if(len > 1)
                   {
                       char[] lenScs = (len+"").toCharArray();
                       for(char c: lenScs)
                       {
                           chars[j++] = c;
                       }
                   }
                   //record new segment  start
                   start = i;
               }
           }
           return j;
            
        }
    

  • 0
    G

    @guo6 well, not really, start is another pointer though


Log in to reply
 

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