给定一个字符串,对字符串进行压缩,返回压缩后的长度,并把压缩后的字符存入原字符串的前面部分。如字符串['a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'd'],压缩后的结果为ab12c2d,返回长度为7,把压缩结果存入原字符串后的结果为ab12c2dbbbbbbccd。
public int compress(char[] chars) { int index = 0; int cur = 0; int count = 1; while(index < chars.length) { if(index + 1 < chars.length && chars[index] == chars[index + 1]) { index++; count++; } else { chars[cur++] = chars[index++]; if(count > 1) { char[] nums = String.valueOf(count).toCharArray(); for(char ch : nums) { chars[cur++] = ch; } } count = 1; } } return cur; }