-
Notifications
You must be signed in to change notification settings - Fork 0
/
string-compression.java
45 lines (32 loc) · 1.01 KB
/
string-compression.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
/* String Compression
Time Complexity: O(n) & Space Complexity: O(n)
*/
class Solution{
// String Compression without frequency count
String compression1(String str){
String s = "" + str.charAt(0);
for(int i=1; i<str.length(); i++)
if( str.charAt(i) != str.charAt(i-1) )
s += str.charAt(i);
return s;
}
// String Compression with frequency count
String compression2(String str){
String s = "" + str.charAt(0);
int count = 1;
for(int i=1; i<str.length(); i++){
// if duplicates then increment counter
if( str.charAt(i) == str.charAt(i-1) )
count++;
else{
if(count > 1){ // for more than 1 character
s += count;
count = 1; // reset to 1 if no duplicates
}
s += str.charAt(i);
}
}
if(count > 1) s += count; // handling last character count
return s;
}
}