-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressString.java
More file actions
49 lines (45 loc) · 1.23 KB
/
CompressString.java
File metadata and controls
49 lines (45 loc) · 1.23 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
package Class08_String2;
/*
* Given a string, replace adjacent, repeated characters with the character
* followed by the number of repeated occurrences. If the character does not
* has any adjacent, repeated occurrences, it is not changed.
*
* Assumptions
* The string is not null
* The characters used in the original string are guaranteed to be ‘a’ - ‘z’
* There are no adjacent repeated characters with length > 9
*
* Examples
* “abbcccdeee” → “ab2c3de3”
*/
public class CompressString {
public String compress(String input) {
if (input == null || input.isEmpty()) {
return input;
}
StringBuilder sb = new StringBuilder();
sb.append(input.charAt(0));
int slow = 0;
int fast = 1;
int count = 1;
while (fast < input.length()) {
if (input.charAt(slow) == input.charAt(fast)) {
while (fast < input.length() && input.charAt(slow) == input.charAt(fast)) {
count++;
fast++;
}
sb.append(String.valueOf(count));
// slow = fast++;
count = 1;
} else {
sb.append(input.charAt(fast));
slow = fast++;
}
}
return sb.toString();
}
public static void main(String[] args) {
CompressString sol = new CompressString();
System.out.println(sol.compress("1"));
}
}