leetcode-刪除最外層的括號

題目

https://leetcode-cn.com/problems/remove-outermost-parentheses/

思路

  • 使用棧,遍歷字符串,遇到左括號就壓入,遇到右括號就彈出,當棧爲空時,說明當前index是外層要捨去的括號,根據下標之間的關係即可找到“原語”
  • 另外一種思路:使用兩個變量left和right,初始化left = 1,right = 0;這樣可以忽略外層的左括號,方便後面判斷left != right時可以追加到res,而不會受到外層左括號的影響。

AC代碼

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    string removeOuterParentheses(string S) {
        string res = "";
        int left = 1;
        int right = 0;
        for(int i = 1;i < S.size();i++)
        {
            if(S[i]=='(')
                left++;
            else    
                right++;
            //判斷
            if (left != right)
                res.push_back(S[i]);
            else 
            { //相等,說明左右括號配對,所以外層括號不能壓入
                right = 0;
                left = 1;
                i++; //忽略外層的左括號
            }
        }
        return res;
    }
};

int main()
{
    string s = "(()())";
    Solution so;
    cout << so.removeOuterParentheses(s) <<endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章