0. 题目
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
1. C++版本
思想:
其实很简单,就是使用栈的思想,将所有括号入栈,当栈顶元素是"(",当前元素是")",那么就将栈里面的"("弹出,依次类推处理"[]","{}"。最后如果栈空,说明所有括号匹配
bool isValid(string s) {
stack<char> mystack;
char topBracket;
for (int i=0; i<s.size(); ++i) {
if (!mystack.empty())
topBracket = mystack.top();
if ((s[i]==')' && topBracket=='(') || (s[i]==']' && topBracket=='[') || (s[i]=='}' && topBracket=='{'))
mystack.pop();
else
mystack.push(s[i]);
}
if (mystack.empty())
return true;
else
return false;
}
2. python版本
def isValid(s):
"""
:type s: str
:rtype: bool
"""
mystack = []
topBracket = ''
for index, bracket in enumerate(s):
if mystack:
topBracket = mystack[-1]
if (bracket==')' and topBracket=='(') or (bracket==']' and topBracket=='[') or (bracket=='}' and topBracket=='{'):
mystack.pop()
else:
mystack.append(bracket)
if mystack:
return False
return True
网友评论