Longest Valid Parentheses
2016-01-10 22:29
274 查看
每日算�'2595——leetcode系列
问题 Longest Valid Parentheses
Difficulty: HardGiven 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.
class Solution { public: int longestValidParentheses(string s) { } };
翻译
最长有效括号
难度系数:中等给定一个仅'25E4��包含
'('或
')'的字符串,找出其中最长有效括号组成的子集的长度。
字符串
"(()",它的最长有效号符子�%;B�是
"()",长度为2。
另一个例子
")()())",它的最长有效括号子集是
"()()",长度是4。
思路
假定:起始匹配位置startIndex=-1;最大匹配长度maxLen=0,当前遍历的索引�'25B8�i:遍历字符串:
遍历到的字符有两种情况:
当前字符为左括号,压栈, startIdnex = i;
当前字符为右括号
如果栈为空,表示没有匹配的左括号,无任何操作
如果栈不空,出栈;
经过上面的第二步操作后,栈有两种情况:
栈空, 则i-startIndex为当前找到的匹配长度,检查i-startIndex是否比maxLen
更大,如果更大就更新maxLen;
栈不空,则当前栈顶元素t是上次匹配的最后位置。,检查i-t
是否比ml更大,使得ml得以更新。
'0A注:因为入栈的一定是左括号,显然没�'9C�必要将它们本身入
栈,应该入栈的是该字符在字符串中的索引。
代码
class Solution { public: void nextPermutation(vector<int>& nums) { size_t len = nums.size(); if (len == 1 || len == 0){ return; } int firstBreakNum = -1; size_t firstBreakIndex = -1; for (size_t i = len ;i > '253Cspan class="hljs-number">1; --i){ if (nums[i-1] > nums[i-2]){ firstBreakNum = nums[i-2]; firstBreakIndex = i - 2; '2520 break; } } // 没找到打破升序规律的,那就全部升序排列 if (firstBreakNum == -1){ reverse(nums.begin(), nums.end()); return; } for (size_t i = len; i > 1; --i){ if (nums[i-1] > firstBreakNum){ swap(nums[i-1]'252C nums[firstBreakIndex]); break; } } auto iter = nums.begin(); for (size_t i = 0; i < firstBreakIndex + 1; ++i){ '20 iter++; } reverse(iter, nums.end()); } };
还可以继续优化
相关文章推荐
- Python抓取和解析网页
- kruscal算法求最小生成树总结
- C#版三层登录
- java_61_SE lesson8
- Dagger2 使用初步
- android studio 开发经验积累
- Install spark cluster
- HDU1247(经典字典树)
- Android之极光推送发送自定义消息
- 交换机上的三种端口模式
- Android之极光推送发送自定义消息
- 获取屏幕高度和宽度 的方法
- Google 打算用 QUIC 协议替代 TCP/UDP
- numpy的安装
- Dubbo spring mvc整合示例
- java调用phantomjs采集ajax加载生成的网页
- 彻底解决 LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- android 摇一摇
- 黑马程序员——数组篇
- C++学习笔记42——重载操作符之箭头操作符