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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章