LeetCode 32 括號匹配
阿新 • • 發佈:2018-09-05
nth 入棧 ati bstr () return -- ava class
[LeetCode 32] Longest Valid Parentheses
題目
Given a string containing just the characters ‘(‘ and ‘)‘, find the length of the longest valid (well-formed) parentheses substring.
測試案例
Input: "(()" Output: 2 Explanation: The longest valid parentheses substring is "()" Input: ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()"
思路
采用棧數據結構。棧中存放各字符的下標。初始時裏面放入-1。
- 從左至右依次遍歷每個字符。當前字符為左括號就進棧。當前字符為右括號時,如果棧中存在左括號,則出棧。否則,入棧。
- 每當都元素,記下標為 i ,進棧時,就用 i - stack.peek() - 1 更新 max。
遍歷結束後,需要用 n - stack.peek() - 1 更新 max。
代碼如下
class Solution { public int longestValidParentheses(String s) { int max = 0, n = s.length(), temp, index = 0; if(n == 0){ return 0; } int[] stack = new int[n + 1]; stack[index++] = -1; for(int i = 0; i < n; i++){ if(s.charAt(i) == ‘(‘ || (temp = stack[index - 1]) == -1 || s.charAt(temp) == ‘)‘){ if((temp = i - stack[index - 1] - 1) > max){ max = temp; } stack[index++] = i; } else{ index--; } } if((temp = n - stack[index - 1] - 1) > max){ max = temp; } return max; } }
LeetCode 32 括號匹配