C# Solution


  • 1
    J

    Iterate over the array, count and use a current ptr to update the array in place.

     public int Compress(char[] chars) {
                int i = 0;
                int ptr = 0;
    
                while (i < chars.Length)
                {
                    int count = 1;
                    char ch = chars[i];
                    i++;
    
                    while (i < chars.Length && chars[i] == ch)
                    {
                        count++;
                        i++;
                    }
    
                    chars[ptr++] = ch;                
    
                    if (count > 1)
                    {
                        foreach (var item in count.ToString().ToCharArray())
                        {
                            chars[ptr++] = item;                        
                        }
                    }
                }
    
                return ptr;
        }
    

Log in to reply
 

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