-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringCompression.java
More file actions
36 lines (34 loc) · 1 KB
/
stringCompression.java
File metadata and controls
36 lines (34 loc) · 1 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
public class stringCompression {
public static void main(String[] args) {
String a = "aabcccccaaa";
String result = stringCompress(a);
System.out.println(result);
}
/*
* Given a string a compress it as follows
* aaabbcccaad -> a3b2c3a2d1
* if a.length() == compressedLength return a
*/
public static String stringCompress(String a) {
if (a.length() == 0)
return a;
StringBuilder answer = new StringBuilder();
char prev = a.charAt(0);
answer.append(a.charAt(0));
int count = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == prev) {
count++;
} else {
answer.append(count);
count = 1;
prev = a.charAt(i);
answer.append(a.charAt(i));
}
}
answer.append(count);
if (answer.length() >= a.length())
return a;
return answer.toString();
}
}