20. 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.

Subscribe to see which companies asked this question.

括号匹配

C++(3ms):

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         stack<char> m ;
 5         for (char c : s){
 6             if (c == '(' || c=='{' || c=='['){
 7                    m.push(c) ;
 8             }else{
 9                 if (m.empty())
10                     return false ;
11                 if (c == ')' && m.top()!='(')
12                     return false ;
13                 if (c == '}' && m.top()!='{')
14                     return false ;
15                 if (c == ']' && m.top()!='[')
16                     return false ;
17                 m.pop();
18             }
19         }
20         if (m.empty())
21            return true ;
22         else
23            return false ;
24     }
25 };
原文地址:https://www.cnblogs.com/mengchunchen/p/6624549.html