Advertisement
1988coder

443. String Compression

Nov 27th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1. /*
  2. Time Complexity: O(N)
  3. Space Complexity: O(1)
  4.  
  5. N = length of chars array.
  6. */
  7. class Solution {
  8.     public int compress(char[] chars) {
  9.         if (chars == null || chars.length == 0) {
  10.             return 0;
  11.         }
  12.         if (chars.length == 1) {
  13.             return 1;
  14.         }
  15.         int index = 0;
  16.         int ansIndex = 0;
  17.        
  18.         while(index < chars.length) {
  19.             char curChar = chars[index];
  20.             int count = 0;
  21.             while (index < chars.length && chars[index] == curChar) {
  22.                 count++;
  23.                 index++;
  24.             }
  25.             chars[ansIndex++] = curChar;
  26.             if (count > 1) {
  27.                 for (char c : Integer.toString(count).toCharArray()) {
  28.                     chars[ansIndex++] = c;
  29.                 }
  30.             }
  31.         }
  32.         return ansIndex;
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement