码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 20 Valid Parentheses stack的应用

时间:2016-03-16 20:44:38      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

判断括号是否合法

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 };

 

Leetcode 20 Valid Parentheses stack的应用

标签:

原文地址:http://www.cnblogs.com/onlyac/p/5284913.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!