LeetCode:Longest Valid Parentheses
2016-05-30 21:08
369 查看
Longest Valid Parentheses
Total Accepted: 63715 TotalSubmissions: 282480 Difficulty: Hard
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.
Subscribe to see which companies asked this question
Hide Tags
Dynamic Programming String
Hide Similar Problems
(E) Valid Parentheses
思路:
使用stack来保存未匹配的“括号”的下标,然后求下标之间的最大差值。
c++ code:
class Solution { public: int longestValidParentheses(string s) { int n = s.length(); stack<int> st; for (int i = 0; i < n; i++) { if (s[i] == '(') st.push(i); else { if (!st.empty()) { if (s[st.top()] == '(') st.pop(); else st.push(i); } else st.push(i); } } int a = n, b = 0; int ans = 0; while(!st.empty()) { b = st.top(); st.pop(); ans = max(ans, a-b-1); a = b; } ans = max(ans, a); return ans; } };
相关文章推荐
- listView优化
- guava常用简化操作
- KMP算法总结
- poj 2559
- iOS-URLconnection
- 简单介绍,基于ldirectord的高可用lvs-dr调度器
- 自定义异步AsyncTask
- MySQL中函数CONCAT及GROUP_CONCAT
- 36. Valid Sudoku
- 让sql语句不排序,按照in语句的顺序返回结果mysql:SELECT*FROMEVENTWHER
- 【动态规划】求二维矩阵的最大和子矩阵
- Linux 忘记root密码并重置root密码
- [NOIP2002]均分纸牌题解
- C#通用类型转换方法
- [编程之美]发帖“水王”问题
- 上拉刷新,下拉加载PullToRefreshLayout
- 计算机网络——万维网
- 【刷题之路】二叉树按层打印
- javascript闭包
- Android设计模式之观察者模式(Observer Pattern)