LeetCode 1021. 刪除最外層的括號

寫在前面: 挺簡單的一道棧應用,定義一個string來記錄結果,用棧記錄過程就行了,需要加兩個判斷來去掉外圍的括號

歡迎關注我的力扣github倉庫,有JavaScript和C++兩個版本,每日更新
C++代碼:

class Solution {
public:
    string removeOuterParentheses(string S) {
        string res;
        stack<char> stack;
        for(int i=0;i<S.length();i++){
            if(S[i]=='('){
                if(!stack.empty())
                    res+=S[i];
                stack.push(S[i]);
            }
            else{
                res+=S[i];
                stack.pop();
                if(stack.empty()) 
                    res.pop_back();          
            }
        }
        return res;
    }
};

JS代碼:

/**
 * @param {string} S
 * @return {string}
 */
var removeOuterParentheses = function(S) {
    var ch=[],res='';   //ch爲棧,res存放返回結果
    for(let i=0;i<S.length;i++){
        if(S[i]=='('){
            if(ch.length>0) //最外層的不被加入res中
                res+=S[i];
            ch.push(S[i]);
        }
        else{
            res+=S[i];
            ch.pop();
            if(ch.length==0)    //最外層的不被加入res中
                res=res.substr(0,res.length-1);
        }
    }
    return res;
};

題目地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章