443. String Compression - LeetCode
Posted okokabcd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了443. String Compression - LeetCode相关的知识,希望对你有一定的参考价值。
Question
Solution
题目大意:把一个有序数组压缩,
思路:遍历数组
Java实现:
public int compress(char[] chars) {
if (chars.length == 0) return 0;
StringBuilder sb = new StringBuilder();
char cur = chars[0];
int sum = 1;
for (int i = 1; i <= chars.length; i++) {
if (i < chars.length && chars[i] == cur) {
sum++;
} else {
sb.append(String.valueOf(cur));
if (sum > 1) {
sb.append(sum);
}
if (i < chars.length) {
cur = chars[i];
sum = 1;
}
}
}
char[] compressChar = sb.toString().toCharArray();
for (int i = 0; i < compressChar.length; i++) {
chars[i] = compressChar[i];
}
return sb.length();
}
以上是关于443. String Compression - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章
leetcode443. String Compression