leetcode栈--5、valid-parentheses(有效括号)

题目描述
 
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.
 
解题思路:遇到任意一种左括号插入栈,遇到右括号,判断栈顶是否与其匹配,不匹配则无效,最后栈为空则有效
 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4        if(s.empty())
 5             return true;
 6         stack<char> ss;
 7         int n = s.size();
 8         for(int i=0;i<n;i++)
 9         {
10             if(s[i] == '(' || s[i] =='[' || s[i] == '{')
11             {
12                 ss.push(s[i]);
13             }
14             else
15             {
16                 if(ss.empty())
17                     return false;
18                 else
19                 {
20                     if(ss.top() == '(' && s[i] == ')')
21                     {
22                         ss.pop();
23                     }
24                     else if(ss.top() == '[' && s[i] == ']')
25                     {
26                         ss.pop();
27                     }
28                     else if(ss.top() == '{' && s[i] == '}')
29                     {
30                         ss.pop();
31                     }
32                     else
33                     {
34                         return false;
35                     }
36                 }
37             }
38         }
39         if(ss.empty())
40             return true;
41         else
42             return false; 
43     }
44 };

 

posted @ 2017-06-06 21:34  qqky  阅读(179)  评论(0编辑  收藏  举报