• LeetCode题解(20)--Valid Parentheses


    https://leetcode.com/problems/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.

    思路:

    考察stack的应用。

    我的AC代码:

     1 class Solution {
     2 public:
     3     bool isValid(string s) {
     4         int n=s.size();
     5         if(n%2==1)
     6             return false;
     7         stack<char> a;    //push,pop,top,size
     8          for(int i=0;i<n;i++){
     9             if(s[i]=='('|| s[i]=='['||s[i]=='{') 
    10                 a.push(s[i]);
    11             else if (a.empty()==false &&( (a.top()=='(' && s[i]==')') || (a.top()=='[' && s[i]==']') || (a.top()=='{' && s[i]=='}') ) )
    12                 a.pop();
    13             else 
    14                 return false;
    15          }
    16          if(a.empty())
    17             return true;
    18          else return false;
    19     }
    20 };
  • 相关阅读:
    Static了解和复习继承。
    复习篇1.对象和封装
    第一章笔记
    A + B Problem II
    Number Sequence
    Fibonacci Again
    8615 快乐
    8635 气球
    大牛之路II
    8617 阶乘数字和
  • 原文地址:https://www.cnblogs.com/aezero/p/4558532.html
Copyright © 2020-2023  润新知