【LeetCode】Valid Parentheses & Generate Parentheses & Longest Valid Parentheses

本文介绍了生成有效括号组合的方法及如何找到字符串中最长的有效括号子串,提供了详细的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

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

参考:

http://www.cnblogs.com/remlostime/archive/2012/11/06/2757711.html

http://www.2cto.com/kf/201310/251552.html

http://blog.youkuaiyun.com/pickless/article/details/9141935



思路:

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        string str;
        vector<string> ret;
        generateParenthesisCore(ret,"",0,0,n);
        return ret;
    }
    void generateParenthesisCore(vector<string> &ret,string str,int lnum,int rnum,const int n)
    {
   		if(lnum > n)	return;
    	if(lnum + rnum == 2*n)
    		ret.push_back(str);
   		
		generateParenthesisCore(ret,str+'(',lnum + 1,rnum,n);
		if(lnum > rnum)
			generateParenthesisCore(ret,str+')',lnum,rnum+1,n);
	}
};




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.

参考:

http://blog.youkuaiyun.com/jellyyin/article/details/9887959



class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> stk;///////////////////////////////
        
        int maxlen = 0, lastleft = -1;
        int i = 0;
        while(i<s.size())
        {
            if(s[i] == '(')
            {
                stk.push(i);
            }
            else if(s[i] == ')' && !stk.empty())
            {
                stk.pop();
                if(stk.empty()) maxlen = max(maxlen,i-lastleft);///////////////////////////////// 
                else            maxlen = max(maxlen,i-stk.top());
            }
            else
                lastleft = i;//////////////////////////////// 
            i++;////////////////////////////////////
        }
        return maxlen;
    }
};


http://blog.youkuaiyun.com/doc_sgl/article/details/12252443
</pre><pre name="code" class="cpp">class Solution {
public:
    int longestValidParentheses(string s) {
        int size = s.size();
        if(size < 2) return 0;///////////////////////////特殊处理 
        vector<int> longest(size,0);
        int maxl = 0;
        for(int i = size-2;i>=0;i--)////////////////从size-2开始 
        {
            if(s[i] == '(')
            {
                int j = i+1+longest[i+1];//去除本配好对的下一个符号
                if(j< size && s[j] == ')')
                {
                    longest[i] = longest[i+1] + 2;//////////////////////////////////////    i+1
                    if(j+1<size)
                     longest[i] += longest[j+1];//加上下一个段
                }
                maxl = max(maxl,longest[i]);///////////////////////////////////////////// 更新 
            }
            //printf("%c i = %d, lo = %d, max = %d\n",s[i],i,longest[i],maxl);
        }
        return maxl;
    }
};





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.

class Solution {
public:
    bool isValid(string s) {
        int size = s.size();
        stack<char> stk;
        while(size--)
        {	
        	if(stk.size() == 0 || !ispair(stk.top(),s[size]))
        		stk.push(s[size]);
       		else
       			stk.pop();
		}
		return stk.empty();
    }
    bool ispair(char ch1,char ch2)
    {
    	return ((ch1 == ')' && ch2 == '(')||(ch1 == '}' && ch2 == '{')||(ch1 == ']' && ch2 == '['))	; 
	}
};







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值