一个代码可以工作,而经过一小部分更改后代码就无法工作

-2 c++

题=leetcode题=1047

删除字符串中所有相邻的重复项 - LeetCode

1047. 删除字符串中所有相邻的重复项

给你一个s由小写英文字母组成的字符串。重复删除包括选择两个相邻相同的字母并将其删除。

我们反复进行重复删除,s直到我们不再能为止。

在完成所有此类重复删除后,返回最终字符串。可以证明答案是唯一的

示例1:

输入: s = "abbaca"
输出: "ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb",因为字母相邻且相等,这是唯一可能的移动。这一举动的结果是字符串是“aaca”,其中只有“aa”是可能的,所以最终的字符串是“ca”。

示例2:

输入: s = "azxxzy"
输出: "ay"

限制条件:

  • 1 <= s.length <= 105
  • s由小写英文字母组成。

这段代码正在运行

class Solution {
public:
    string removeDuplicates(string s) {
        int n = s.length();
        string ans = "";
        for(int i=0;i<n;i++){
            if((ans.length() > 0) && s[i] == ans[ans.length()-1]){
                ans.pop_back();
            }
            else{
                ans.push_back(s[i]);
            }
        }
        return ans;
    }
};
Run Code Online (Sandbox Code Playgroud)

ans.length() > 0对第 7行进行小幅更改后 ans.length() - 1 >= 0 ,代码无法正常工作

class Solution {
public:
    string removeDuplicates(string s) {
        int n = s.length();
        string ans = "";
        for(int i=0;i<n;i++){
            if((ans.length() - 1 >= 0) && s[i] == ans[ans.length()-1]){  // line no.7
                ans.pop_back();
            }
            else{
                ans.push_back(s[i]);
            }
        }
        return ans;
    }
};
Run Code Online (Sandbox Code Playgroud)

显示溢出错误。为什么会发生这种情况

Jar*_*d42 5

由于unsigned整数 ( length())

ans.length() - 1 >= 0总是true。( 0u - 1 == std::numeric_limits<unsigned>::max())

您可能会更改为:

ans.length() >= 1或者!ans.empty()

您可以使用 for-range 和适当的方法完全避免索引:

std::string removeDuplicates(std::string& s) {
    std::string ans = "";
    for (auto c : s){
        if (!ans.empty() && c == ans.back()) {
            ans.pop_back();
        } else {
            ans.push_back(c);
        }
    }
    return ans;
}
Run Code Online (Sandbox Code Playgroud)