-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStringCompress.java
More file actions
55 lines (48 loc) · 1.07 KB
/
StringCompress.java
File metadata and controls
55 lines (48 loc) · 1.07 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
51
52
53
54
55
package edu.java.chap1;
/*
* simple string compress
* input: aaabbbccc
* output:a3b3c3
* if output is longer than input, then return input instead.
*/
public class StringCompress {
public static void Stringbuffer(){
StringBuffer sb = new StringBuffer();
sb.append(1);
System.out.println(sb.toString());
}
//time complex: O(n), space complex: O(n)
public static void compress1(String str){
if(str.length() == 0) {
System.out.println("please enter a string longer than 0 length");
return;
}
char pos = str.charAt(0);
int num = 0;
StringBuffer sb = new StringBuffer();
for(int i = 0; i<str.length();i++){
if(str.charAt(i) == pos){
num++;
}
else{
sb.append(pos);
sb.append(num);
pos = str.charAt(i);
num = 1;
}
}
sb.append(pos);
sb.append(num);
String result = sb.toString();
if(result.length()>str.length()){
System.out.println(str);
}else{
System.out.println(result);
}
}
public static void main(String[] args) {
String str = "aaabbbcccddd";
//String str2 = "abcdefg";
compress1(str);
}
}