算法设计与分析第八周leetcode

  1. Longest Valid Parentheses

https://leetcode.com/problems/longest-valid-parentheses/description/
Difficulty:Hard
Total Accepted:151.5K
Total Submissions:629.9K

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 "()()"

解答过程:
一开始思路是计算可以与’(‘匹配的’)'数量来计算结果,但是这样算的答案不是不一定是字串的,例如"(()(()“用这个方法算出来的是4,将两个”()“都计算了,但这两个”()"并非连在一起的子字符串,正确答案应该为2
下面是一开始的错误代码:

class Solution {
public:
	stack<int> STACK;//0代表左括号,1代表右括号
	int longestValidParentheses(string s) {
		int result=0;
		for (int i = 0; i < s.size(); i++) {
			if (s[i] == '(') {
				STACK.push(0);
			}
			else {
				if (STACK.size() != 0) {
					result += 2;
					STACK.pop();
				}
			}
		}
		return result;
	}
};

为了正确计算子字符串的长度,很明显需要将无法匹配的括号位置单独记录下来,上面的例子"(()(()“就需要将第0和第3号位置的”("单独记录位置以标记这两个端点。处理之后,两个子字符串范围分别为[1 ~ 2] 和 [4 ~ 5] ,取子字符串长度最长即为答案。
下面为最终代码:

class Solution {
public:
	stack<int> STACK;//输入的数字代表对应的位置
	int longestValidParentheses(string s) {
		int result = 0;
		for (int i = 0; i < s.size(); i++) {
			if (STACK.size() != 0 && s[STACK.top()] == '('&&s[i]==')') {
				STACK.pop();
			}
			else {
				STACK.push(i);
			}
		}

		if (STACK.size() == 0) {
			result = s.size();

		}
		else {
			int stackSize = STACK.size(), back = 0, front = 0;
			result = s.size() - STACK.top() - 1;
			for (int i = 0; i < stackSize - 1; i++) {
				back = STACK.top();
				STACK.pop();
				front = STACK.top();
				result = max(back - front - 1, result);
			}
			result = max(STACK.top(), result);
		}
		return result;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值