首页 > 其他 > 详细

[LeetCode]Valid Parentheses

时间:2015-11-12 11:34:08      阅读:260      评论:0      收藏:0      [点我收藏+]

题目描述:(链接)

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.

解题思路:

用一个stack实现

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         for (int i = 0; i < s.size(); ++i) {
 5             switch (s[i]) {
 6                 case (:
 7                 case {:
 8                 case [: {
 9                     cache.push(s[i]); 
10                     break;
11                 }
12                 case ): {
13                     if (!isSuitable(()) {
14                         return false;
15                     }
16                     break;
17                 }
18                 case }: {
19                     if (!isSuitable({)) {
20                         return false;
21                     }
22                     break;
23                 }
24                 case ]: {
25                     if (!isSuitable([)) {
26                         return false;
27                     }
28                     break;
29                 }
30             }
31         }
32         
33         if (!cache.empty()) return false;
34         
35         return true;
36     }
37 private:
38     stack<int> cache;
39     bool isSuitable(int character) {
40         if (cache.empty()) {
41             return false;
42         }
43         
44         int ch = cache.top();
45         if (ch != character) {
46             return false;
47         }
48         
49         cache.pop();
50         
51         return true;
52     }
53 };

 

[LeetCode]Valid Parentheses

原文:http://www.cnblogs.com/skycore/p/4958094.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!