Description
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
Follow up:
Could you solve it using only O(1) extra space?
Input:
["a","a","b","b","c","c","c"]
Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
即对Char型数组中的字符进行统计,要求原地修改原数组,要注意原始字符的顺序位置
Solution
双指针
- 统计字符,首先想到用 HashMap,但是原题中要求是对连续字符的统计,而不是对整个数组中相同字符的统计,所以 HashMap 并不是好的选择;
- 使用双指针统计个数,anchor 指向当前字符,read遍历数组,判断相邻两个字符是否相同;
- write 指针用来修改数组,当 read 判断到相邻两个字符不相同时,对原数组修改,连续字符个数为 read - anchor +1;
- 返回修改后数组长度 → 最后write指针指向的index值;
- 需要注意当某字符个数不是个位数时,需要用char类型分开存储,方法为 ( int + "" ).toCharArray();
class Solution {
public int compress(char[] chars) {
int write = 0, anchor = 0;
for(int read = 0;read < chars.length;read++){
if(read + 1 == chars.length || chars[read + 1] != chars[read]){ //对 read + 1 == chars.length 的判断需要放前面,不然会溢出
chars[write++] = chars[anchor];
if(read > anchor){
for(char c : ("" + (read - anchor +1)).toCharArray()){
chars[write++] = c;
}
}
anchor = read + 1;
}
}
return write;
}
}
网友评论