1249. Minimum Remove to Make Valid Parentheses

还是习惯于用堆栈解决括号问题

class Solution {
public:
    string minRemoveToMakeValid(string s) {
        stack<string> mystack;
        for (int ii=0;ii<s.size();ii++){
            if (s[ii]!=')'){
                string temp = "";
                temp += s[ii];
                mystack.push(temp);
            }
            else{ //input: ")"
                string result = "";
                while(!mystack.empty()){
                    if (mystack.top()=="("){
                        /// judge () is avaliable
                        result = "(" + result + ")";
                        mystack.pop();
                        mystack.push(result);
                        result = "";
                        break;
                    }
                    else{
                        result = mystack.top() + result;
                        mystack.pop();
                    }
                }
                if (result.size()!=0){
                    mystack.push(result);
                }
            }
        }
        
        // after gain final stack, then gain resutls
        string res = "";
        while(!mystack.empty()){
            if (mystack.top()!="(" && mystack.top()!=")"){
                res = mystack.top() + res;
            }
            mystack.pop();
        }
        return res;
    }
};
发布了361 篇原创文章 · 获赞 18 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/zeroQiaoba/article/details/104495311