【Leetcode 20】Valid Parentheses
阿新 • • 發佈:2018-12-11
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
題目翻譯:
一個string的串,裡邊放了幾種符號 [ ] ( ) { } 要求這些符號合理的組成括號。
需要考慮的邊界值 :
[]) 返回false
“” 這種要返回 true
[](){} 這種要返回 true
解題思路:
這個思路很簡單,使用stack即可,如果stack最上邊的符號是(,而新進來的符號是 ) 這樣可以彈出stack,括號不配對,就繼續壓棧。需要注意的是,如果stack是空的,那麼stack.top()就會出錯,所以,要在判斷中加上 !stack.empty() 這樣來確定是否出錯。
#include <stack> #include <iostream> #include <string> using namespace std; class Solution { public: bool isValid(string s) { int n = s.length(); stack<char> sta; for (int i = 0; i < n; i++) { if (s[i] == '}' && !sta.empty() && sta.top() == '{') { sta.pop(); continue; } if (s[i] == ']' && !sta.empty() && sta.top() == '[') { sta.pop(); continue; } if (s[i] == ')' && !sta.empty() && sta.top() == '(') { sta.pop(); continue; } sta.push(s[i]); } if (sta.empty()) return true; else return false; } }; int main() { string s; getline(cin, s); Solution so; bool n = so.isValid(s); cout << n << endl; system("pause"); return 0; }