编程之法第一章习题——6.重复字符的压缩

题目


压缩连续出现的字符,例如:字符abcbc由于无连续字符,压缩后的字符串还是“abcbc”。压缩后输出的格式要求为又重复的字符,按字符重复的次数+字符输出,例如,字符串xxxyyyyyyz压缩后输出为3x6yz

代码


#include <iostream>
using namespace std;
class Solution
{
public:
    string suppressStr(string&str)
    {
        int count = 1;
        string result;
        int pos = 0;
        while (pos<str.length())
        {
            count = 0;
            for (int i=pos;i<=str.length();i++)
            {
                if (str[i]==str[pos])
                {
                    count++;
                }
                else if(i==str.length()||str[i]!=str[pos])
                {
                    char temp = '0' + count;
                    if(count!=1)
                        result.insert(result.end(),temp);
                    result.insert(result.end(), str[pos]);
                    pos = i;
                    break;

                }
            }
        }
        return result;
    }
};

思路


遍历字符串,用变量count记录连续出现的次数,以及pos记录第一次出现的位置,然后将次数+该位置的字符插入到新字符串尾部。

猜你喜欢

转载自blog.csdn.net/m0_37316917/article/details/80114509