问题: 把字符串压缩,比如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++; [...]