-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressString.java
More file actions
28 lines (27 loc) · 827 Bytes
/
CompressString.java
File metadata and controls
28 lines (27 loc) · 827 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
package leetcode.string;
/**
* @ClassName CompressString
* @Description 字符串压缩 https://leetcode-cn.com/problems/compress-string-lcci/
* @Author changxuan
* @Date 2020/9/12 下午9:08
**/
public class CompressString {
public String compressString(String S) {
if (S == null) return null;
if (S.length() == 0) return "";
char[] SArr = S.toCharArray();
StringBuilder res = new StringBuilder();
res.append(SArr[0]);
int count = 1;
for (int i = 1; i < SArr.length; ++i) {
if (SArr[i] == SArr[i - 1]){
count++;
}else {
res.append(count).append(SArr[i]);
count = 1;
}
}
res.append(count);
return S.length() > res.length() ? res.toString() : S;
}
}