• valid parentheses


    Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

    The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
     
    思路分析:
    首先遍历字符串,
    如果是左括号(3种)则入栈,
    否则(说明是右括号),首先判定栈是否已空,
              若空(说明当前的右括号不会有左括号与之匹配),返回false,
              否则,出栈,并且将这一元素与当前正在遍历的元素进行匹配,若是不匹配则返回false(无效的括号字符集),否则遍历继续进行。
    遍历完括号字符串之后,若是,栈为空,返回true
    否则返回false,程序结束!
     
    代码如下:
     1 #include<iostream>
     2 #include<stack>
     3 #include<vector>
     4 using namespace std;
     5 
     6 class Solution {
     7 private:
     8     stack<char> sta;
     9 public:
    10     bool isValid(string s) {
    11         int len = s.length();
    12         for (int i = 0; i < len; ++i)
    13         {
    14             if (s[i] == '(' || s[i] == '[' || s[i] == '{')
    15                 sta.push(s[i]);
    16             else
    17             {
    18                 if (sta.empty())//这个地方不先判空,则遇到()] 这种情况,程序就直接崩溃了,因为对一个空栈top,你懂的
    19                     return false;
    20                 char temp = sta.top();
    21                 sta.pop();
    22                 if (temp=='('&&s[i]==')'||temp=='['&&s[i]==']'||temp=='{'&&s[i]=='}')
    23                 {
    24                     ;
    25                 }
    26                 else return false;
    27 
    28             }
    29         }
    30         if (sta.empty())
    31             return true;
    32         else return false;
    33     }
    34 };
    35 
    36 int main()
    37 {
    38     Solution test;
    39     string val = "()()]";
    40     bool result = test.isValid(val);
    41     cout << result << endl;
    42     return 0;
    43 }
    手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
  • 相关阅读:
    id4的数据库持久化写法
    docker 加速镜像的地址收集
    mongodb 的ID转换实体要注意的地方
    net core3.0 常用封装状态码总结
    JAVA8—————StringJoiner类
    BigDecimal加减乘除
    mysql 查询奇偶数
    Java遍历Map对象的方式
    Java中List, Integer[], int[]的相互转换
    springboot 读取resources下的文件然后下载
  • 原文地址:https://www.cnblogs.com/chess/p/4733505.html
Copyright © 2020-2023  润新知