面试题 01.06. 字符串压缩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public String compressString(String S) {
StringBuilder sb = new StringBuilder();

int i = 0, j = 0;
while (j < S.length()) {
while (j < S.length() && S.charAt(j) == S.charAt(i)) {
j++;
}

// now: j == S.length() or S[i] != S[j]
sb.append(S.charAt(i)).append(j - i);
i = j;
}

return sb.length() < S.length() ? sb.toString() : S;
}
}

References

面试题 01.06. 字符串压缩