LeetCode32 Longest Valid Parentheses

问题描述:
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: “(()”
Output: 2
Explanation: The longest valid parentheses substring is “()”
Example 2:

Input: “)()())”
Output: 4
Explanation: The longest valid parentheses substring is “()()”
题源:here;完整代码:here
思路:
两种方案:1 动态规划;2 使用堆栈。
方案1
动态规划最重要的是转移条件。设有如下变量:
record:记录每个位置的有效符号个数
s:输入字符串
我们首先将record全部置零,然后定义转移条件:
if s[i] == ‘)’ and s[i-1] == ‘(’:
record[i] = record[i-1]+2
if s[i] == ‘)’ and s[i-1] == ‘)’ and s[i-record[i-1]-1] == ‘(’:
record[i] = record[i-1]+record[i-record[i-1]-2]+2
代码如下:

class Solution {
public:
	int longestValidParentheses(string s) {
		vector<int> dp(s.size(), 0);
		int res = 0;
		for (int i = 1; i < s.size(); i++) {
			if (s[i] == ')') {
				if (s[i - 1] == '(')
					dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
				else if (i - dp[i - 1] - 1 >= 0 && s[i - dp[i - 1] - 1] == '(') 
					dp[i] = (i - dp[i - 1] >= 2?dp[i - dp[i - 1] - 2]:0) + dp[i - 1] + 2;
				res = max(res, dp[i]);
			}
		}
		return res;
	}
};

方案2
我们知道堆栈可以方便的判断一组输入是否合法;我们稍加变换就可以作为这道题的解法:
当遇到’('时压入其索引号
当遇到‘)’是吐出索引号,并记录当前索引号与吐出索引号后的堆栈栈顶之差(作为合法括号组合长度)
代码如下:

class Solution {
public:
	int longestValidParentheses(string s) {
		stack<int> ss;
		int res = 0;
		ss.push(-1);
		for (int i = 0; i < s.size(); i++) {
			if (s[i] == '(') ss.push(i);
			else {
				ss.pop();
				if (ss.empty()) ss.push(i);
				else res = max(res, i - ss.top());
			}
		}
		return res;
	}
};

如有疑惑,强烈推荐阅读here

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值