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

相關文章
相關標籤/搜索