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

[LeetCode] Valid Parentheses

时间:2015-06-13 15:35:04      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:

This is a classic problem of the application of stacks. The idea is, each time we meet a ({ or[, we push it to a stack. If we meet a )} or ], we check if the stack is not empty and the top matches it. If not, return false; otherwise, we pop the stack. Finally, if the stack is empty, returntrue; otherwise, return false.

The code is as follows, very straight-forward.

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         stack<char> paren;
 5         for (int i = 0; i < s.length(); i++) {
 6             if (s[i] == ( || s[i] == { || s[i] == [)
 7                 paren.push(s[i]);
 8             else if (s[i] == ) || s[i] == } || s[i] == ]) {
 9                 if (paren.empty()) return false;
10                 if (!match(paren.top(), s[i])) return false;
11                 paren.pop();
12             }
13         }
14         return paren.empty();
15     }
16 private:
17     bool match(char s, char t) {
18         if (t == )) return s == (;
19         if (t == }) return s == {;
20         if (t == ]) return s == [;
21     }
22 };

 

[LeetCode] Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4573462.html

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