版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoguaihai/article/details/84927916
文章目录
1. 题目描述:
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 “()()”
2. 思路分析:
题目的意思是给定一个括号序列的字符串,找到最长有效括号子序列的长度。
此题可用栈来实现,建立一个栈用来存放字符在字符串中的位置,遍历整个字符串,如果遇到左括号,则当前位置入栈;如果遇到右括号,则弹出栈顶元素,此时分2种情况讨论:
(1)如果此时栈不为空,则表示此次成功匹配,这时匹配的长度为当前位置减去栈顶元素值;
(2)如果此时为空,则表示弹出的并非左括号,而是起始位置标识值,则表示此次匹配失败,则需要当前位置入栈表示下次匹配的起始值。
3. Java代码:
源代码
:见我GiHub主页
代码:
public static int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
// 为了方便计算push一个匹配开始位置的前一个位置
stack.push(-1);
int maxLen = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) { // 表示未匹配,重新push下一次匹配开始位置的前一个位置
stack.push(i);
} else {
// i-stack.peek()表示当前匹配的长度
maxLen = Math.max(maxLen, i - stack.peek());
}
}
}
return maxLen;
}