Simple and concise JAVA solution


  • 0
    J
    class Solution 
    {
        public int compress(char[] chars) 
        {
            int count = 0;
            int i = 0;
            while (i < chars.length)
            {
                char cur = chars[i];
                chars[count++] = cur;
                int j = i + 1;
                while (j < chars.length && chars[j] == cur) j++;
                if (j - i > 1)
                {
                    String countChar = String.valueOf(j - i);
                    for (int c = 0; c < countChar.length(); c++) chars[count++] = countChar.charAt(c);
                }
                i = j;
            }
            return count;
        }
    }
    

Log in to reply
 

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