zoukankan      html  css  js  c++  java
  • 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.

    Solution:

     1 class Solution {
     2 public:
     3     bool isValid(string s) {
     4         int len = s.length();
     5         if(len % 2 != 0) return false;
     6         else{
     7             stack<char> sta;
     8             sta.push(s[0]);
     9             for(int i = 1; i < len; i++){
    10                 if(sta.empty()) sta.push(s[i]);
    11                 else{
    12                     if(s[i] == pair(sta.top())) sta.pop();
    13                     else sta.push(s[i]);
    14                 }
    15             }
    16             if(sta.empty()) return true;
    17             else return false;
    18         }
    19     }
    20     char pair(char ch){
    21         switch(ch){
    22             case '(': return ')';
    23             case ')': return '(';
    24             case '[': return ']';
    25             case ']': return '[';
    26             case '{': return '}';
    27             case '}': return '{';
    28         };
    29     }
    30 };
  • 相关阅读:
    3.node.js AssertionError: false == true错误解决
    9.获取当前时区时间和utc时间的工具方法
    2.Express封装mysq方法
    1.Express初识
    poj 3617
    前缀和
    pop 反序列化
    Reverse前两个题
    前两个Web题
    Misc
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4414997.html
Copyright © 2011-2022 走看看