leetcode 括号匹配系列

Valid Parentheses
 
AC Rate: 712/2328

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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len = s.length();
		if( 0 == len) return true;
		stack<char> sta;
		char peek;
		for(int i = 0; i < len; ++i)
		{
			switch(s[i])
			{
			case '(':
				sta.push(s[i]);
				break;
			case ')':
				if(sta.empty() || sta.top() != '(')
					return false;
				sta.pop();
				break;
			case '[':
				sta.push(s[i]);
				break;
			case ']':
				if(sta.empty() || sta.top() != '[')
					return false;
				sta.pop();
				break;
			case '{':
				sta.push(s[i]);
				break;
			case '}':
				if(sta.empty() || sta.top() != '{')
					return false;
				sta.pop();
				break;
			}
		}
		return sta.empty();
    }
};

Generate Parentheses
 
AC Rate: 645/2090

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:

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

class Solution {
	void dfs(int nleft,int nright,string &cur,vector<string>& res)
	{
		if(0 == nleft && 0 == nright)
		{
			res.push_back(cur);
			return;
		}
		char ch = cur[cur.length()-1];
		string backup = cur;
		if(nleft > 0)
		{
			cur += "(";
			dfs(nleft-1,nright,cur,res);
			cur = backup;
		}
		if(nright > nleft)
		{
			cur += ")";
			dfs(nleft,nright-1,cur,res);
			cur = backup;
		}
	}
public:
    vector<string> generateParenthesis(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<string> res;
		if(0 == n) return res;
		string tmp;
		dfs(n,n,tmp,res);
		return res;
    }
};

Longest Valid Parentheses
 
AC Rate: 476/2748

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.

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

感觉这个题是需要一些技巧的,用一个栈记录左括号的位置,并且用一个变量last记录上一次匹配失败的位置。初始化last为-1,然后往后顺序遍历

括号序列,如果碰到左括号则压栈,如果是右括号则看栈是否空,如果空,则说明这个右括号是个野括号,那么更新last变量,如果当前栈非空,那么

说明有左括号可以匹配,则弹出一个,再判断当前栈是否为空,如果为空,则说明从last到当前位置是全部可以匹配的,所以更新长度i-last,如果

出栈之后发现栈非空,则说明从last到当前位置这段序列,左括号要多于右括号,至于栈里的这个左括号是否能在之后的序列中匹配是无法预知的,所以

暂时更新长度为i-stack.top()。

上代码

class Solution {
public:
    int longestValidParentheses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
	    int len = s.length();
		if(0 == len) return 0;
		int maxlen = 0,last = -1;
		stack<int> lefts;//stack of left parentheses
		for(int i = 0; i < len; ++i)
		{
			if(s[i] == '(')
				lefts.push(i);
			else if(lefts.empty())
				last = i;
			else
			{
				lefts.pop();
				if(lefts.empty())
					maxlen = max(maxlen,i-last);
				else
					maxlen = max(maxlen,i-lefts.top());
			}
		}
		return maxlen;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值