问题描述
给定一个字符数组,里面包含一些重复的字符,要求将数组进行压缩(重复的字符用数字表示),比如 aabbbcdd
压缩成 a2b3cd2
。题目链接:**点我**
样例输入输出
输入:[“a”,”a”,”b”,”b”,”c”,”c”,”c”]
输出:[“a”,”2”,”b”,”2”,”c”,”3”]
输入:[“a”,”b”,”b”,”b”,”b”,”b”,”b”,”b”,”b”,”b”,”b”,”b”,”b”]
输出:[“a”,”b”,”1”,”2”]
问题解法
按题意模拟压缩,遍历数组,对每个字符与前个字符进行判断,如果相等,则计算加一,否则获取相等字符的个数,然后将其转成对应的字符。在这里,为了避免进行字符翻转操作,先计算出数字的位数,然后从后往前放数字字符。代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution { public int compress(char[] chars) { int count = 1; int index = 0; for (int i = 1; i <= chars.length; i++) { if (i < chars.length && chars[i] == chars[i - 1]) { count++; continue; }
chars[index] = chars[i - 1]; index++; if (count == 1) { continue; }
int temp = count; int num = 0; while (temp > 0) { temp /= 10; num++; }
int tempIndex = index + num - 1; while (count > 0) { chars[tempIndex] = (char) (count % 10 + '0'); count /= 10; tempIndex--; index++; } count = 1; } return index; } }
|