给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。数组
示例 1:网络
输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
code
示例 2:leetcode
输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"
字符串
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/longest-valid-parentheses
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。
class
//错误写法,这里贴出来与后面的AC代码作对比。错误的缘由在于“)()())”的解为2,记数的方式不行 public class Main { public static void main(String[] args) { String s = ")()())"; // String s = ")()((())"; System.out.println(longestValidParentheses(s)); } public static int longestValidParentheses(String s) { int ans = 0; int tmp = 0; Stack<String> stack = new Stack<>(); if (s.length() != 0) { stack.push(String.valueOf(s.charAt(0))); } for (int i=1; i<s.length(); i++) { if (stack.peek().equals("(")) { if (String.valueOf(s.charAt(i)).equals(")")) { stack.pop(); tmp += 2; } else { stack.push(String.valueOf(s.charAt(i))); tmp = 0; } } else { stack.push(String.valueOf(s.charAt(i))); tmp = 0; } if (tmp > ans) { ans = tmp; } } return ans; } }
//仍是用栈,只是如今将数组下标存入栈中。 //遇到'('就将下标存如栈中,遇到')'就将栈顶的下标出栈,而后计算距离 public class Main { public static void main(String[] args) { // String s = ")()())"; String s = ")()((())"; System.out.println(longestValidParentheses(s)); } public static int longestValidParentheses(String s) { int ans = 0; Stack<Integer> stack = new Stack<Integer>(); stack.add(-1); for (int i=0; i<s.length(); i++) { if (s.charAt(i) == '(') { stack.push(i); } else { stack.pop(); if (stack.empty()) { stack.add(i); } else { ans = Math.max(ans, i-stack.peek()); } } } return ans; } }