知识点

字符串

思路

遍历chars数组,利用临时变量temp存储上一次最后出现的字符,l存储最后出现的字符的长度。对于出现当前字符与temp不相同的情况,则将之前的字符与长度都更新到答案vector中

其中,出现次数可以使用to_string 函数转换为字符串,再依次加入答案数组中。

代码c++

#include <numeric>
#include <string>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param chars char字符型vector
     * @return char字符型vector
     */
    vector<char> compress(vector<char>& chars) {
        // write code here
        vector<char>ans;
        int temp = chars[0];
        int l = 1;
        for (int i = 1; i < chars.size(); i++) {
            if (chars[i] == temp) 
            {
                l++;
            } 
          else {
                ans.push_back(temp);
                string s = to_string(l);
      if (l != 1)for (int i = 0; i < s.size(); i++)ans.push_back(s[i]);
                temp = chars[i];
                l = 1;

              }

        }
        ans.push_back(temp);
        string s = to_string(l);
     if (l != 1)for (int i = 0; i < s.size(); i++)ans.push_back(s[i]);
        return ans;
    }
};