leetcode 32 -- Longest Valid Parentheses
2015-06-18 13:23
483 查看
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.类似暴力求解,对每个子串进行验证,记录其括号匹配的长度,括号匹配原则,任意时刻,左括号个数一定大于右括号个数,且起始不能为右括号。时间复杂度O(n^2),超时。
2.新建一个数组(长度和s相同)作为辅助记录字符串s的括号匹配过程,用栈来帮我们测试是否满足括号匹配,有满足匹配则把对应下标置为1,不满足为0,最后遍历辅助数组,最长连续为1的长度就是我们所需要的结果,时间复杂度为O(n),AC
代码:
思路1int longestValidParentheses(char* s) { char *p = s; char *q; int ret = 0; int left; int right; while(*p != '\0'){ //首字符不能为右括号 if(*p == ')'){ ++p; continue; }else if(*p == '('){ left = 1; right = 0; q = p+1; while(*q != '\0'){ //printf("s:%s\n", q); //sleep(1); if(*q == '('){ left++; }else if(*q == ')'){ right++; } //满足匹配更新,不满足跳出循环 if(right == left){ if(right+left > ret){ ret = right+left; //printf("ret:%d\n", ret); } }else if(right > left){ p = q; ++q; break; } ++q; } ++p; } } return ret; }
手动测试过正确,但是leetcode上面显示超时
思路2
class Solution { public: int longestValidParentheses(string s) { stack<int>sk; vector<int>ivec(s.length()); //初始化 for(int &i : ivec){ i = 0; } for(int i = 0; i < s.length(); ++i){ //注意栈保存的是对应字符的下标 if(s[i] == '('){ sk.push(i); }else if(s[i] == ')' && !sk.empty()){ //当为')'时,栈若不为空,则里面一定为'(',满足匹配,标记为1 ivec[i] = 1; ivec[sk.top()] = 1; sk.pop(); } } int ret= 0; int tmp = 0; //找最长连续为1的 for(const int &i : ivec){ if(i == 1){ tmp++; }else{ tmp = 0; } if(ret < tmp){ ret = tmp; } } return ret; } };
相关文章推荐
- C# 读取和修改指定config文件内的配置
- GRE写作论证论据素材大全—社会发展阶段
- 各种排序算法稳定性分析
- Codeforces Round #307 (Div. 2) D. GukiZ and Binary Operations(数学)
- 各国虚拟主机大盘点
- linux_远程登陆服务器并互相复制文件
- Android中使用setBackgroundDrawable错误提示:The method setBackgroundDrawable(Drawable) from the type View is
- java 8种基本数据类型
- 锁屏或按Home键后继续播放音乐
- 为什么VS2008的静态库release版比debug版还要大?
- visual studio设置为使用IIS运行网站时加载项目遇到权限问题的解决方法
- Shuttle ESB(四)——宣布订阅模式实例介绍(1)
- WebView中详解
- 剑指offer-第三章高质量代码(树的子结构)
- easyui
- redis安装
- Bash 中的特殊字符大全
- 实现无限极分类-递归实现
- 伟大源于自律
- Sublime Text 3 汉化+激活教程