-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringCompress.java
More file actions
54 lines (47 loc) · 1.35 KB
/
Copy pathStringCompress.java
File metadata and controls
54 lines (47 loc) · 1.35 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
import java.util.*;
public class StringCompress {
static void compress(char c[]) {
boolean visited[] = new boolean[c.length];
for (int i = 0; i < c.length; i++) {
if (visited[i] == false) {
for (int j = i + 1; j < c.length; j++) {
if (c[i] == c[j]) {
visited[j] = true;
continue;
} else {
System.out.print(c[i]);
break;
}
}
}
}
System.out.print(c[c.length-1]);
}
static void compressString(String s){
StringBuffer sb= new StringBuffer(s.valueOf(s.charAt(0)));
int count = 1;
for(int i=1; i < s.length(); i++){
if(s.charAt(i) == s.charAt(i-1)){
count++;
}
else{
if(count>1){
sb.append(count);
count =1;
}
sb.append(s.charAt(i));
}
}
if(count>1){
sb.append(count);
}
System.out.println(sb);
}
public static void main(String[] args) {
String s= "aaabbccccddaeee";
char ch[]= s.toCharArray();
compress(ch);
System.out.println();
compressString(s);
}
}