Leetcode每日一题练习 ------ 1957. 删除字符使字符串变好

Leetcode 每日一题练习继续讨论:

1957. 删除字符使字符串变好
1957. Delete Characters to Make Fancy String

题解

本题是一道简单题只需每次遇到超过两个连续的相同字符时将该字符忽略。用一个变量记录当前字符,另一个变量记录字符重复的次数。若次数为2且新字符等于当前字符则忽略新字符,如此直到字符串末尾即构造得到新字符串。

代码

class Solution {
public:
    string makeFancyString(string s) {
        string result;
        char current = s[0];
        int count = 0;
        for (auto ch : s){
            if (count == 2 && current == ch){
                continue;
            }else if(current == ch){
                count++;
            }else{
                current = ch;
                count = 1;
            }
            result.push_back(ch);
        }
        return result;
    }
};
2 Likes

来了!刷题佬!tieba_095
建议贴一两个举例 :bili_040:

2 Likes

来了刷题佬!

1 Like