-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringCompression.java
More file actions
23 lines (23 loc) · 876 Bytes
/
Copy pathStringCompression.java
File metadata and controls
23 lines (23 loc) · 876 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int compress(char[] chars) {
if(chars.length == 0) return -1;
int start = 0;
for(int end = 0, count = 0; end < chars.length; end++) {
count++;
if(end == chars.length-1 || chars[end] != chars[end + 1] ) {
//We have found a difference or we are at the end of array
chars[start] = chars[end]; // Update the character at start pointer
start++;
if(count != 1) {
// Copy over the character count to the array
char[] arr = String.valueOf(count).toCharArray();
for(int i=0;i<arr.length;i++, start++)
chars[start] = arr[i];
}
// Reset the counter
count = 0;
}
}
return start;
}
}