Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Time Complexity: O(N)
- Space Complexity: O(1)
- N = length of chars array.
- */
- class Solution {
- public int compress(char[] chars) {
- if (chars == null || chars.length == 0) {
- return 0;
- }
- if (chars.length == 1) {
- return 1;
- }
- int index = 0;
- int ansIndex = 0;
- while(index < chars.length) {
- char curChar = chars[index];
- int count = 0;
- while (index < chars.length && chars[index] == curChar) {
- count++;
- index++;
- }
- chars[ansIndex++] = curChar;
- if (count > 1) {
- for (char c : Integer.toString(count).toCharArray()) {
- chars[ansIndex++] = c;
- }
- }
- }
- return ansIndex;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement