LeetCode算法入门- Longest Valid Parentheses -day12
生活随笔
收集整理的這篇文章主要介紹了
LeetCode算法入门- Longest Valid Parentheses -day12
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
LeetCode算法入門- Longest Valid Parentheses -day12
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 “()()”
思路分析:
此題同樣可以用堆這個結(jié)構(gòu)來實現(xiàn),建立一個堆棧來存放字符在字符串中的位置,遍歷整個數(shù)組,如果遇到左括號,則當前位置入棧;如果遇到右括號,則彈出棧頂元素,這個時候分成兩種情況討論:
算法實現(xiàn)如下:
class Solution {public int longestValidParentheses(String s) {Stack<Integer> stack = new Stack<>();//為了方便計算push一個匹配開始位置的前一個位置stack.push(-1);int result = 0;for(int i = 0; i < s.length(); i++){if(s.charAt(i) == '('){stack.push(i);}else{stack.pop();//空時表示匹配失敗,將當前元素的位置push進去if(stack.isEmpty()){stack.push(i);}else{//i - stack.peek()表示當前匹配的長度,取最大值result = Math.max(result, i - stack.peek());}}}return result;} }總結(jié)
以上是生活随笔為你收集整理的LeetCode算法入门- Longest Valid Parentheses -day12的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mac 黑窗口连接mysql_mac上终
- 下一篇: Java常用设计模式————建造者模式