【问题标题】:Why is my code Time Limit Exceeded while a really similar code is not (Leetcode 1249)?为什么我的代码超过了时间限制,而真正相似的代码却没有(Leetcode 1249)?
【发布时间】:2021-05-07 00:31:55
【问题描述】:

我正在解决https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/

说明:给定一个由 '(' , ')' 和小写英文字符组成的字符串 s。

您的任务是删除最少数量的括号('(' 或 ')',在任何位置),以便生成的括号字符串有效并返回任何有效字符串。

我尝试实现一个 O(1) 空间解决方案,即

string minRemoveToMakeValid(string s) {
        string ans;
        string fa;
        int l=0;
        for(char c:s){
            if(c=='(') l++;
            else if(c==')'){
                if(l==0) continue;
                l--; 
            }
            ans = ans + c;
        }
        for(int i=ans.size()-1;i>=0;i--){
            if(ans[i]=='(' && l>0){
                l--;
                continue;
            }
            fa = fa + ans[i];
        }
        reverse(fa.begin(),fa.end());
        return fa; 
    }

但它会抛出 Time Limit Exceeded。

类似的代码正在运行并被接受,并且没有抛出 TLE,我无法理解导致这种情况的差异

string minRemoveToMakeValid(string s) {
        int open=0;
        string t;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='(')open++;
            else if(s[i]==')')
            {
                if(open==0)continue;
                open--;
            }
            t+=s[i];
        }
        string ans;
        for(int i=t.size()-1;i>=0;i--)
        {
            if(t[i]=='(' && open>0)
            {
                open--;
                continue;
            }
            ans+=t[i];
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }

请帮助我理解并感谢您的帮助。

【问题讨论】:

  • 顺便说一句,这不是O(1) 空间解决方案
  • 这使得推理变得更加困难,因为这两个版本都有极其难以描述的变量名称,唯一的共同变量是ans,它在不同版本中用于不同的事情。
  • 是的,它奏效了。我现在将尝试找出为什么 += 比我使用的那个更好。 @Bathsheba

标签: c++ string


【解决方案1】:

除非你有一个聪明的编译器,否则+= 可能会更快,因为它只是将char 连接到现有的std::string (当达到字符串内存限制时可能会有几个分配,但那不会' t 发生在每次调用 +=)。

std::string 的重载 + 运算符后跟赋值回 self 很可能会导致字符串复制。

聪明的编译器应该能转换

fa = fa + ans[i];

fa += ans[i];

但 C++ 标准不要求这个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2018-08-23
    • 1970-01-01
    • 2022-11-18
    相关资源
    最近更新 更多