forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathString Compression.java
27 lines (26 loc) · 1.03 KB
/
String Compression.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public int compress(char[] chars) {
int pt1=0,pt2=1; // pt1 is slow pointer to update chars & pt2 is fast pointer to calculate the count for pt1;
int count=1; // since every element will occur atleast once.
for(;pt2<chars.length;pt2++){
if(chars[pt2]==chars[pt2-1]){
count++;
}
else {
chars[pt1] = chars[pt2-1]; // change pt1 to last same character
pt1 = setGroupCount(count,chars,++pt1); // if (count > 1) then update chars with count
count=1; // reset to 1 for new element
}
}
chars[pt1] = chars[pt2-1]; // same as above else block for last element
return setGroupCount(count, chars, ++pt1);
}
private int setGroupCount(int count,char[] chars, int pt){
if(count>1){
String str = String.valueOf(count);
for(int i=0;i<str.length();i++)
chars[pt++]=str.charAt(i);
}
return pt;
}
}