forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompressString.java
60 lines (53 loc) · 1.87 KB
/
CompressString.java
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 com.rampatra.strings;
/**
* @author rampatra
* @since 2019-04-08
*/
public class CompressString {
/**
* Compress a string, consisting of only alphabets, such that the compressed string contains the letter and
* a number next to it representing the number of times it is repeated. Also, compress only if the letter is
* repeated more than once and ignore it occurs just once.
* EXAMPLE:
* Input: aaabbcdd
* Output: a3b2cd2
* <p>
* Time Complexity: O(n)
* Space Complexity: O(n)
* where,
* n is the number of characters in the input string
*
* @param str the input string consisting on only alphabets
* @return the compressed string
*/
private static String compress(String str) {
// some basic validation
if (str.length() == 0) {
throw new IllegalArgumentException("Empty String");
}
StringBuilder sb = new StringBuilder();
int letterCount = 0;
for (int i = 0; i < str.length(); i++) {
/*
When the current character is a different one, append the previous character and its count to the
result, and finally, reset the counter
*/
if (i != 0 && str.charAt(i) != str.charAt(i - 1)) {
sb.append(str.charAt(i - 1));
if (letterCount > 1) sb.append(letterCount);
letterCount = 0;
}
letterCount++;
}
// last character
sb.append(str.charAt(str.length() - 1));
if (letterCount > 1) sb.append(letterCount);
return sb.toString();
}
public static void main(String[] args) {
System.out.println(compress("a"));
System.out.println(compress("aabbcc"));
System.out.println(compress("aabcc"));
System.out.println(compress("aaaabbbccaad"));
}
}