20. Valid Parentheses

错误解法:

"[])"就会报错,没考虑到出现')'、']'、'}'时,stack为空的情况,这种情况也无法匹配

  1. class Solution {
  2. public:
  3. bool isValid(string s) {
  4. if(s.empty())
  5. return false;
  6. stack<char> st;
  7. st.push(s[]);
  8. for(int i = ;i < s.size();i++){
  9. if(s[i] == '(' || s[i] == '[' || s[i] == '{')
  10. st.push(s[i]);
  11. else if(s[i] == ')'){
  12. if(st.top() == '(')
  13. st.pop();
  14. else
  15. return false;
  16. }
  17. else if(s[i] == ']'){
  18. if(st.top() == '[')
  19. st.pop();
  20. else
  21. return false;
  22. }
  23. else if(s[i] == '}'){
  24. if(st.top() == '{')
  25. st.pop();
  26. else
  27. return false;
  28. }
  29. }
  30. return st.empty() ? true : false;
  31. }
  32. };

正确解法:

  1. class Solution {
  2. public:
  3. bool isValid(string s) {
  4. int length = s.size();
  5. if(length < )
  6. return false;
  7. stack<char> result;
  8. for(int i = ;i < length;i++){
  9. if(s[i] == '(' || s[i] == '[' || s[i] == '{')
  10. result.push(s[i]);
  11. else{
  12. if(result.empty())
  13. return false;
  14. if(s[i] == ')' && result.top() != '(')
  15. return false;
  16. if(s[i] == ']' && result.top() != '[')
  17. return false;
  18. if(s[i] == '}' && result.top() != '{')
  19. return false;
  20. result.pop();
  21. }
  22. }
  23. return result.empty();
  24. }
  25. };

32. Longest Valid Parentheses

https://www.cnblogs.com/grandyang/p/4424731.html

这个题求的是最长的连续匹配正确的符号。

匹配错误只可能是右括号')'存在时,堆中没有左括号'('进行匹配。start用来继续这个连续匹配的开始位置,只有在匹配错误的情况下,这个start才更新。

如果匹配成功后,堆中没有左括号'(',则说明从start到当前都是匹配正确了的;

注意必须用i - position.top(),可能出现这种情况'(()()',如果你使用i - position弹出的那个位置,你永远只可能获得长度为2的,不可能获得连续的长度。

  1. class Solution {
  2. public:
  3. int longestValidParentheses(string s) {
  4. int start = ,res = ;
  5. stack<int> position;
  6. for(int i = ;i < s.size();i++){
  7. if(s[i] == '(')
  8. position.push(i);
  9. else if(s[i] == ')'){
  10. if(position.empty())
  11. start = i + ;
  12. else{
  13. position.pop();
  14. res = position.empty() ? max(res,i - start + ) : max(res,i - position.top());
  15. }
  16. }
  17. }
  18. return res;
  19. }
  20. };

自己写的一个版本,更容易理解:

  1. class Solution {
  2. public:
  3. int longestValidParentheses(string s) {
  4. stack<int> sta;
  5. int res = ;
  6. int left = -;
  7. for(int i = ;i < s.size();i++){
  8. if(s[i] == '(')
  9. sta.push(i);
  10. else{
  11. if(sta.empty())
  12. left = i;
  13. else{
  14. int index = sta.top();
  15. sta.pop();
  16. if(sta.empty())
  17. res = max(res,i - left);
  18. else
  19. res = max(res,i - sta.top());
  20. }
  21. }
  22. }
  23. return res;
  24. }
  25. };

301. Remove Invalid Parentheses

这个题是求删除后所有合法的,并且要求删除次数必须最少。

这个题与前面两个题稍稍有点不同,这个题需要用bfs的方式,把每个位置的字符删除加入队列判断是否合法,一旦有合法的就不再进行删除操作,而是把队列中剩下的进行判断是否合法就行了。

使用了visited数组,这样防止了搜索的重复计算

  1. class Solution {
  2. public:
  3. vector<string> removeInvalidParentheses(string s) {
  4. vector<string> res;
  5. unordered_set<string> visited;
  6. visited.insert(s);
  7. queue<string> q;
  8. q.push(s);
  9. bool finished = false;
  10. while(!q.empty()){
  11. string tmp = q.front();
  12. q.pop();
  13. if(isValid(tmp)){
  14. res.push_back(tmp);
  15. finished = true;
  16. }
  17. if(finished)
  18. continue;
  19. for(int i = ;i < tmp.size();i++){
  20. if(tmp[i] != '(' && tmp[i] != ')')
  21. continue;
  22. string t = tmp.substr(,i) + tmp.substr(i+);
  23. if(!visited.count(t)){
  24. visited.insert(t);
  25. q.push(t);
  26. }
  27. }
  28. }
  29. return res;
  30. }
  31. bool isValid(string s){
  32. int count = ;
  33. for(int i = ;i < s.size();i++){
  34. if(s[i] != '(' && s[i] != ')')
  35. continue;
  36. else if(s[i] == '(')
  37. count++;
  38. else{
  39. if(count <= )
  40. return false;
  41. else
  42. count--;
  43. }
  44. }
  45. return count == ;
  46. }
  47. };

leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、的更多相关文章

  1. [Leetcode][Python]32: Longest Valid Parentheses

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 32: Longest Valid Parentheseshttps://oj ...

  2. 刷题32. Longest Valid Parentheses

    一.题目说明 题目是32. Longest Valid Parentheses,求最大匹配的括号长度.题目的难度是Hard 二.我的做题方法 简单理解了一下,用栈就可以实现.实际上是我考虑简单了,经过 ...

  3. [LeetCode] 32. Longest Valid Parentheses 最长有效括号

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  4. 【一天一道LeetCode】#32. Longest Valid Parentheses

    一天一道LeetCode系列 (一)题目 Given a string containing just the characters '(' and ')', find the length of t ...

  5. leetcode解题报告 32. Longest Valid Parentheses 用stack的解法

    第一道被我AC的hard题!菜鸡难免激动一下,不要鄙视.. Given a string containing just the characters '(' and ')', find the le ...

  6. leetcode 32. Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  7. Java [leetcode 32]Longest Valid Parentheses

    题目描述: Given a string containing just the characters '(' and ')', find the length of the longest vali ...

  8. leetcode problem 32 -- Longest Valid Parentheses

    Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...

  9. [leetcode]32. Longest Valid Parentheses最长合法括号子串

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

随机推荐

  1. ubuntu安装ftp server服务

    原文地址: https://jingyan.baidu.com/article/7908e85c988b23af481ad2ae.html 首先,更新软件源,保证源是最新的,这样有利于下面在线通过ap ...

  2. 【github&&git】5、使用Git拉取GitLab上的项目

    一.安装Git(windows版.其他平台参阅) 去Git的官网,下载安装包,安装时,一路默认 二.配置Git 2.1 在任意地方,创建一个文件夹,保证该文件夹的目录全部是英文 2.2 打开新建的文件 ...

  3. 如何用minitab检测一组数据是否服从正态分布

    打开Minitab之后 点击Stat>Basic Statistics> Normality Test  分析之后若 P value(P值)>0.05,说明此组数据服从正态分布

  4. canvas离屏技术与放大镜实现

    教程所示图片使用的是 github 仓库图片,网速过慢的朋友请移步>>> (原文)canvas 离屏技术与放大镜实现. 更多讨论或者错误提交,也请移步. 利用canvas除了可以实现 ...

  5. C#中的out、ref、params详解

    out参数: 如果你在一个方法中,返回多个相同类型的值的时候,可以考虑返回一个数组.但是,如果返回多个不同类型的值的时候,返回数组就不行了,那么这个时候,我们可以考虑使用out参数.out参数就侧重于 ...

  6. JS window与document

    开头语:嗯~~~~~~~~~ 正文如下 一.window window是Javascript中的最高级对象,它是document.location和history对象的父对象.正因为window是一个 ...

  7. pygame中模块说明

    参考博客:https://blog.csdn.net/qq_27717921/article/details/53231762 pygame模块概览 1.display模块 功能:生成windows窗 ...

  8. python之初识函数

    函数: 函数是对功能或动作的封装. 函数的语法和定义: def 函数名(): 函数体 调用函数: 函数名() 函数返回值: return : 返回 def yue(): print("拿出手 ...

  9. Nginx 反向代理工作原理简介与配置详解

    Nginx反向代理工作原理简介与配置详解   by:授客  QQ:1033553122   测试环境 CentOS 6.5-x86_64 nginx-1.10.0 下载地址:http://nginx. ...

  10. linux网络 skb_buff

    sbk_buff中的data_len指的是尾部带的page数据的长度,len指的是总共的data的长度,len-data_len是第一个线性buf的数据长度. sk_buff->len:表示当前 ...