-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringCompression.java
More file actions
53 lines (48 loc) · 1.45 KB
/
StringCompression.java
File metadata and controls
53 lines (48 loc) · 1.45 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
public class StringCompression {
public static String compress(String str) {
StringBuilder sb = new StringBuilder();
int count = 0;
char ch = str.charAt(0);
sb.append(ch);
for (int i = 0; i < str.length(); i++) {
if (ch == str.charAt(i)) {
count++;
} else {
if (count>1){
sb.append(count);
}
sb.append(str.charAt(i));
ch = str.charAt(i);
count = 1;
}
}
if(count>1)
sb.append(count);
return sb.toString();
}
public static String compress1(String str){
StringBuffer sb= new StringBuffer();
for(int i=0;i<str.length();i++){
int count=1;
while(i<str.length()-1&&str.charAt(i)==str.charAt(i+1)){
count++;
i++;
}
sb.append(str.charAt(i));
if(count>1){
sb.append(count);
}
}
return sb.toString();
}
// Time Complexity: O(n)
// Space Complexity: O(n)
public static void main(String[] args) {
String s = "aaabbcccdd";
System.out.println(compress(s));
System.out.println(compress("abc"));
System.out.println(compress("aaabc"));
System.out.println(compress1("abc"));
System.out.println(compress1("aaabc"));
}
}