-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStringCompression.java
67 lines (44 loc) · 1.39 KB
/
StringCompression.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
package swordPointOffer;
/**
* @Author: Wenhang Chen
* @Description:字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。 示例1:
* <p>
* 输入:"aabcccccaaa"
* 输出:"a2b1c5a3"
* 示例2:
* <p>
* 输入:"abbccd"
* 输出:"abbccd"
* 解释:"abbccd"压缩后为"a1b2c2d1",比原字符串长度更长。
* 提示:
* <p>
* 字符串长度在[0, 50000]范围内。
* @Date: Created in 21:40 5/12/2020
* @Modified by:
*/
public class StringCompression {
public String compressString(String S) {
if (S == null || S.length() < 1)
return S;
char ch = S.charAt(0);
int num = 0;
StringBuilder st = new StringBuilder();
for (int i = 0; i < S.length(); i++) {
if (ch == S.charAt(i)) {
num++;
} else {
st.append(ch);
st.append(num);
ch = S.charAt(i);
num = 1;
}
}
st.append(ch);
st.append(num);
if (st.length() < S.length()) {
return st.toString();
} else {
return S;
}
}
}