Leetcode 20 Valid Parentheses stack的应用

判断括号是否合法

1.用stack存入左括号“([{”,遇到相应的右括号“)]}”就退栈

2.判断stack是否为空,可以判断是否合法

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         stack<char> sc;
 5         char in[] ="([{";
 6         char out[] =")]}";
 7         for(string::size_type i = 0; i < s.size(); ++i){
 8             for(int j = 0; j < 3; ++j){
 9                 if(in[j] == s[i]) sc.push(s[i]);
10             }
11             for(int j = 0; j < 3; ++j){
12                 if(out[j] == s[i]){
13                     if(sc.empty()) return false;
14                     else if(sc.top() == in[j]) sc.pop();
15                     else return false;
16                 } 
17             }
18         }
19         return sc.empty();
20     }
21 };
原文地址:https://www.cnblogs.com/onlyac/p/5284913.html