问题:
把字符串压缩,比如aaabbbbc, 压缩后成为:a3b4c1。
分析:
这题很简单,我们只需要从头到尾遍历一遍字符串即可。首先设置一个计数器count, 每次“指针移位”的时候,判断当前字符是否与前一个字符相等,如果相等,count++, 指针继续下移,否则,我们需要对前面已经遍历的字符串进行处理,然后重新初始化count,直到字符串遍历结束。这题的关键是对最后一个字符的处理。
public static String compress(char[] array) {
if (array == null || array.length == 0 ) return null;
int count = 1;
StringBuilder sb = new StringBuilder(); //save the compressed string
for (int index = 1; index < array.length; index++) {
if (array[index] == array[index - 1]) {
count++;
} else {
sb.append(array[index - 1]);
sb.append(count);
count = 1;
}
}
//important! add the last character to the stringbuilder.
sb.append(array[array.length - 1]);
sb.append(count);
return sb.toString();
}
扩展:
给定一个排序的整数数组,去除里面重复的值。比如:{1,1,1,1,2,2,5,5,5,} 变为 {1,2,5}。