-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringCompression.java
More file actions
60 lines (50 loc) · 1.36 KB
/
StringCompression.java
File metadata and controls
60 lines (50 loc) · 1.36 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package String;
import java.util.Stack;
/**
* Author - archit.s
* Date - 04/09/18
* Time - 11:20 PM
*/
public class StringCompression {
public int compress(char[] chars) {
int start = 0;
int end = 0;
int N = chars.length;
int count = 0;
for(int i=0;i<N;){
char first = chars[i];
while(end < N && first == chars[end]){
end++;
}
if((end-1) > i){
int extra = 0;
int temp = end-i;
Stack<Integer> s = new Stack<>();
while(temp>0){
s.push(temp%10);
temp /= 10;
}
chars[start] = first;
while(!s.empty()){
extra++;
chars[start+extra] = (char)(s.pop()+48);
}
start = start + extra + 1;
count+=extra+1;
i = end;
}
else{
chars[start] = first;
count++;
start++;
i++;
}
}
return count;
}
public static void main(String[] args) {
char[] c = new char[]{'a', 'a', 'a', 'b', 'b', 'c', 'c'};
System.out.println(new StringCompression().compress(c));
System.out.println(c);
}
}