6、Valid Parentheses 驗證括號
阿新 • • 發佈:2018-12-21
Valid Parentheses
Description:
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
bool isValid(string s) { stack<char> parentheses; // 定義一個棧 for (int i = 0; i < s.size(); ++i) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]); // 如果是左括號 入棧 else { if (parentheses.empty()) return false; // 如果為空 返回false if (s[i] == ')' && parentheses.top() != '(') return false; // 有括號與站定匹配 不匹配返回false if (s[i] == ']' && parentheses.top() != '[') return false; if (s[i] == '}' && parentheses.top() != '{') return false; parentheses.pop(); } } return parentheses.empty(); // 若棧為空則為true }