LeetCode 20. Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.html

An input string is valid if:ide

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.函数

Example 1:spa

Input: "()"
Output: true

Example 2:code

Input: "()[]{}"
Output: true

Example 3:htm

Input: "(]"
Output: false

Example 4:blog

Input: "([)]"
Output: false

Example 5:ip

Input: "{[]}"
Output: true

 

 

这道题看似简单,可是我仍是没有一次AC,思路很简答,就是入栈与出栈,遇到左括号入栈,碰见若是有匹配的括号将其出栈,不然返回false,到最后若是栈空则说明括号是合法且匹配的,相似的题目有Generate ParenthesesLongest Valid Parenthesesget

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         stack<char> sta;
 5         for (auto c : s)
 6         {
 7             if (c == '}')
 8             {
 9                 if (sta.empty() || sta.top() != '{')
10                     return false;
11                 else
12                     sta.pop();
13             }
14             else if (c == ']')
15             {
16                 if (sta.empty() || sta.top() != '[')
17                     return false;
18                 else
19                     sta.pop();
20             }
21             else if (c == ')')
22             {
23                 if (sta.empty() || sta.top() != '(')
24                     return false;
25                 else
26                     sta.pop();
27             }
28             else
29                 sta.push(c);
30         }
31         return sta.empty();
32     }
33 };

有几个地方要注意:一、调用栈的top()函数时必定要先判决栈是否为空,不然会报错;二、多个else if 条件时,必定要用合适的方式进行分类讨论,不然容易重复或者遗漏input

如下是一种更简练的写法:

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         stack<char> parentheses;
 5         for (int i = 0; i < s.size(); ++i) {
 6             if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]);
 7             else {
 8                 if (parentheses.empty()) return false;
 9                 if (s[i] == ')' && parentheses.top() != '(') return false;
10                 if (s[i] == ']' && parentheses.top() != '[') return false;
11                 if (s[i] == '}' && parentheses.top() != '{') return false;
12                 parentheses.pop();
13             }
14         }
15         return parentheses.empty();
16     }
17 };

 

相似的解答请参考:http://www.cnblogs.com/grandyang/p/4424587.html

相关文章
相关标签/搜索