长大后想做什么?做回小孩!

0%

LeetCode——字符串压缩

NO.01.06 字符串压缩 简单

8G1O91.png

思路一:遍历 看到题,没什么好的思路,直接遍历统计。最后比较两个字符串长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public String compressString(String S) {
if (S==null||S.length()<2)return S;
StringBuilder sb=new StringBuilder();
for (int i = 0; i < S.length(); i++) {
int count=1;
char c = S.charAt(i);
while (i<S.length()-1&&c==S.charAt(i+1)){
count++;
i++;
}
sb.append(c).append(count);
}
return sb.length()<S.length()?sb.toString():S;
}

时间复杂度:O(n)


本人菜鸟,有错误请告知,感激不尽!

更多题解和学习记录博客:博客github