加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

[LeetCode] Longest Valid Parentheses

发布时间:2020-12-13 20:10:35 所属栏目:PHP教程 来源:网络整理
导读:Longest Valid Parentheses Given a string containing just the characters '(' and ')' ,find the length of the longest valid (well-formed) parentheses substring. For (() ,the longest valid parentheses substring is () ,which has length = 2. An

Longest Valid Parentheses

Given a string containing just the characters '(' and ')',find the length of the longest valid (well-formed) parentheses substring.

For "(()",the longest valid parentheses substring is "()",which has length = 2.

Another example is ")()())",where the longest valid parentheses substring is "()()",which has length = 4.

解题思路:

题意找到最长有效括号的子串长度。求最大问题,第1想法就是动态计划,但是,通项公式真不好找。喜刷刷http://bangbingsyb.blogspot.jp/2014/11/leetcode-longest-valid-parentheses.html中有相干说明,我没有理解,

由因而括号问题,可以用栈来实现。这跟判断栈是不是有效不同。注意到,若某个右括号不与前面的某个左括号匹配,那末,这个右括号可以作为子串分割标记。大体思想是,若遇到左括号,无条件将左括号的下标入栈。若遇到右括号,若栈顶是左括号与之匹配,将左括号出栈,更新最大的长度值。若栈顶没有左括号与之匹配,将该右括号的下标入栈,作为分割字符。代码以下:

class Solution { public: int longestValidParentheses(string s) { int len=s.length(); stack<int> st; int maxLen=0; for(int i=0; i<len; i++){ if(s[i]=='('){ st.push(i); }else{ if(!st.empty()&&s[st.top()]=='('){ st.pop(); maxLen = max(maxLen,st.empty()?i+1:i-st.top()); }else{ st.push(i); } } } return maxLen; } };


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读