1,题目要求
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.
2,题目思路
遍历整个字符数组即可,可以重新创建一个字符数组来记录,这样比较明了。不过若是想要在O(1)的空间内完成,就直接在原字符串数组上进行操作即可。
值得注意的一点是,如何将一个整数化成单个单个的字符形式。一开始想了一些办法,但是都不好。
最好的办法是利用to_string( )将数字转化为字符串,然后再用for(char c : str)方法获得整个字符串中的单个单个的字符。
3,程序源码
class Solution {
public:
int compress(vector<char>& chars) {
vector<char> res;
int charPos = 0;
for(int i = 0;i<chars.size();i++)
{
if((i+1) == chars.size() || chars[i]!=chars[i+1])
{
res.push_back(chars[i]); //将对应的字符添加到res中
if(i-charPos>=1) //出现次数超过一次
{
string tmp = to_string(i-charPos+1);
for(char c : tmp)
res.push_back(c);
}
charPos = i+1;
}
}
chars = res;
return (int)res.size();
}
};
利用O(1)空间操作:
class Solution {
public:
int compress(vector<char>& a) {
int i = 0, t = 0;
for (int j = 0; j < a.size(); ++j) //遍历
if (j+1 == a.size() || a[j+1] != a[j]) { //到达结尾或者发现不同的元素
a[t++] = a[j]; //记录下当前的字母,然后t++
if (j >= i + 1) { //字母出现的次数超过1次,就记录下来
string s = to_string(j-i+1); //将出现的次数转化为字符串的形式,然后按char写入到原字符数组中
for (char c:s) a[t++] = c;
}
i = j + 1;
}
return t;
}
};