各种Parentheses

Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

题目:给一串只包含各种括号的字符串,来判断这个串是否有效,即可以左右匹配。

分析:左右括号匹配,栈的应用之一。如果遇到左括号就压栈,如果遇到右括号,分情况:1 如果此时栈为空,那么该串非法;2如果不空,弹出栈顶与该右括号匹配。

代码:

class Solution {
public:
    bool isValid(string s) {
        int len=s.length();
        if((len & 1)==1)//奇数个肯定不匹配 
            return false;
        stack<char> st;
        int i;
        
        for(i=0;i<len;i++){
            if(s[i]=='(' || s[i]=='{' || s[i]=='[' ){
                st.push(s[i]);
            }else{
                if(st.empty()) return false; //栈中没有左括号来匹配当前的括号
                char t=st.top();
                if((s[i]==')' && t=='(') || (s[i]=='}' && t=='{') || (s[i]==']' && t=='[')){
                    st.pop();
                }
                else break;
            }
        }
        if(st.empty() && (i>=len))//栈为空,字符串也到了末尾
            return true;
        return false;
        
    }
};

Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

题意:给个数n,生成所有合法的括号组合。

分析:可以生成的合法括号序列的个数,是卡特兰数 1/(n+1)C(2n,n-1)个。

具体生成要用递归,基本原则就是左括号的数量要>=右括号的数量,根据上一个valid的判断过程可知。若之前左括号数目==右括号,下一个只能加左括号。

注意代码中leftnum表示还有多少个左括号可以用。

代码:

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        if(n<1) return res;
        string one;
        dfs(res,one,n,n);
        return res;
    }
    
    void dfs(vector<string> &res, string one, int leftnum, int rightnum){//leftnum表示还有多少(没有用
        if(leftnum > rightnum)// 左括号剩余的多,不满足要求,如2,1,说明现在又())不可能满足要求。
            return ;
        if(leftnum==0 && rightnum==0){
            res.push_back(one);
            return ;
        }
        if(leftnum>0){
            one.push_back('(');
            dfs(res, one, leftnum-1,rightnum);
            one.pop_back();
        }
        if(rightnum>0){
            one.push_back(')');
            dfs(res,one, leftnum, rightnum-1);
            one.pop_back();
        }
        
    }
    
};

Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

题目:找一个串中,最长的合法括号长度。

分析:坑的题目,原始办法,取字串,然后一一判断。虽然可以剪枝,但还是超时O(n^3)。

别人的解:O(n),用stack来保存左括号的下标,用last记录最后一次没有匹配的")"的下标。如果遇到左括号,下标压栈。如果遇到右括号,1. 如果此时栈空,当前右括号无法匹配,更新last。2.栈不空,弹出栈顶跟右括号匹配,2.1如果此时栈空,得到一个匹配i-last,2.2如果栈不空,也就是左括号还有剩余,可以获得当前可以得到的匹配长度i-st.top()。

代码:

class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> st;
        int res=0,last=-1;//last 记录最后一个无法匹配的')'
        for(int i=0;i<s.size();i++){
            if(s[i]=='('){
                st.push(i);
            }else{//==')'
                if(st.empty()){ last=i; }//更新最后一个无法匹配的右括号
                else{
                    st.pop();//删除栈顶与')'匹配
                    if(st.empty()){//如果此时栈空,表示到i,是一个标准匹配
                        res=max(res,i-last);
                    } else{//如果不空,说明后面还有可能继续匹配((() i=3时,
                        res=max(res,i-st.top());
                    }
                }
            }//else
        }
        return res;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值