题目:
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
描述:
括号匹配,比较简单的题,借助栈来完成整个过程
(多年之后,重做旧题,有所感慨,毕竟当年连栈式结构都想不明白)
代码:(时间复杂度O(n))
class Solution {
public:
bool isValid(string s) {
stack<char> temp;
for (int i = 0; i < s.size(); ++ i) {
if (s[i] == ')') {
if (temp.size() && temp.top() == '(') {
temp.pop();
} else {
return false;
}
} else if (s[i] == ']') {
if (temp.size() && temp.top() == '[') {
temp.pop();
} else {
return false;
}
} else if (s[i] == '}') {
if (temp.size() && temp.top() == '{') {
temp.pop();
} else {
return false;
}
} else {
temp.push(s[i]);
}
}
return !temp.size();
}
};