首页 > 其他 > 详细

[LeetCode] Valid Parentheses

时间:2015-06-13 15:34:29      阅读:158      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!