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();
}