-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompress1_5.java
More file actions
50 lines (41 loc) · 1.29 KB
/
Copy pathCompress1_5.java
File metadata and controls
50 lines (41 loc) · 1.29 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
50
package String;
import java.util.Arrays;
public class Compress {
/**
* @param args
*/
public static void main(String[] args) {
String str = "aabccccccaaa";
String newStr = compress(str);
System.out.print(newStr);
}
/**Implement a method to perform basic string compression using the counts of repeated characters.
* For example, the string aabccccccaaa would become a2b1c5a3. If the "compressed"
* string would not become smaller than the original string, your method should return the original string.
**/
public static String compress(String str){
if(str == null || str.isEmpty()) return null;
char[] chars = new char[str.length()];
for(int i=0; i<str.length();i++){
chars[i] = str.charAt(i);
}
Arrays.sort(chars);
char compare = chars[0];
int counter =1;
String compress="";
String totalCompress = "";
for(int i=1; i<chars.length; i++){
if(compare==chars[i]){
counter++;
}else{
compress = String.valueOf(compare)+Integer.toString(counter);
totalCompress = totalCompress + compress;
counter=1;
compare = chars[i];
}
}
compress = String.valueOf(compare)+Integer.toString(counter);//This two lines of code is for catching the last char and its size
totalCompress = totalCompress + compress;
return totalCompress;
}
}