面试题 01.06 字符串压缩

简单题,注意边界情况处理即可。

class Solution {
public:
    string compressString(string S) {
        string ans;
        char pre = S[0];
        int cnt = 0;
        for(int i = 0; i < S.size(); ++i)
        {
            if(S[i] == pre) ++cnt;
            if(S[i] != pre) 
            {
                ans.push_back(pre);
                ans += to_string(cnt);
                cnt = 1;
            }
            if(i == S.size() - 1)
            {
                ans.push_back(S[i]);
                ans += to_string(cnt);
            }
            pre = S[i];
        }
        return ans.size() < S.size() ? ans : S;
    }
};

偷懒式写法:

class Solution {
public:
    string compressString(string S) {
        string ans;
        char pre = S[0];
        int cnt = 0;
        S.push_back('#'); // 给原字符串结尾添加一个标记位,这样就不用判断i走到字符串末尾的情况
        for(int i = 0; i < S.size(); ++i)
        {
            if(S[i] == pre) ++cnt;
            else 
            {
                ans.push_back(pre);
                ans += to_string(cnt);
                cnt = 1;
            }
            pre = S[i];
        }
        return ans.size() < S.size() - 1 ? ans : (S.pop_back(), S);
    }
};
发布了21 篇原创文章 · 获赞 32 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/include_not_found_/article/details/104894767