-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressString.java
More file actions
31 lines (31 loc) · 931 Bytes
/
CompressString.java
File metadata and controls
31 lines (31 loc) · 931 Bytes
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
/*
* Implement a method to perform basic string compression using the counts
* of repeated characters. aabcccccaaa would become a2b1c5a3, if the compressed
* string would not be smaller than the original than return the original
* CTCI 1.6
*/
class CompressString
{
public compressString(String s1)
{
//use string builder to create the new striing
//string concatonation in java is terribly inefficient,
//string builder should always be used.
StringBuilder compressed = new StringBuilder();
int count = 1;
compressed.append(s1.charAt(0));
for(int i = 1; i < s1.length(); i++)
{
if(s1.charAt(i) != s1.charAt(i-1))
{
compressed.append(count);
compressed.append(s1.charAt(i))
count = 1;
}
else
{
count++;
}
}
}
}