玩命加载中 . . .

1047-删除字符串中的相邻重复项


LeetCode 1047. Remove All Adjacent Duplicates In String

LeetCode-1047

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.

We repeatedly make duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

Example 1:

Input: s = "abbaca"
Output: "ca"

method: 栈

题意:消掉相邻的重复字符,消掉之后又有重复相邻要继续消掉

直接用字符串当栈,如果当前元素和栈顶元素相同,就出栈

string removeDuplicates(string str) {
    string ret;
    for (auto s : str) {
        if (ret.empty() || ret.back() != s) ret.push_back(s);
        else ret.pop_back();
    }
    return ret;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录