题目链接及描述
443. 压缩字符串 - 力扣(LeetCode)
题目分析
这个题目总体不算太难,如果之前接触过双指针(快慢指针)的话,比较好做。题目可以理解为计算数组中对应各个连续字符出现的次数,并将次数记录下来。可以使用快慢指针解决,慢指针指向连续字符的第一个下标处,快指针不断往后移动,当快指针对应字符和慢指针对应的字符不相等时,说明此时得到了一个连续的同字符。此时可以将慢指针对应的字符和快慢指针间的长度记录下来。
代码编写
class Solution {public int compress(char[] chars) {Deque<Character> list = new ArrayDeque<>();int len = chars.length, slow = 0;for(int fast = 0; fast <= len; fast++){if(fast == len || chars[fast] != chars[slow]){list.addLast(chars[slow]);int diff = fast - slow;if(diff > 1){String str = String.valueOf(diff);for(char ch : str.toCharArray()){list.addLast(ch);}}slow = fast;}}int idx = 0;while(!list.isEmpty()){chars[idx++] = list.pollFirst();}return idx;}
}