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
题意:
符号匹配简化版,之所以称为简化版 是因为这里似乎不需要考虑优先级的问题。
分析:
既然不需要考虑优先级,那么 简单配对即可实现,这里首先使用python 中的list模拟实现栈的功能。如下
Code & Python
class Solution:
def isValid(self, s: str) -> bool:
a=[]
count=0
left = ['(','{','[']
mapping = {')':'(',']':'[','}':'{'}
for brackets in s:
if brackets in left:
a.append(brackets)
else:
if len(a)==0:return False
if a.pop(-1) != mapping[brackets]:
return False
if len(a)==0:
return True
return False
结果:
Runtime: 40 ms, faster than 47.54% of Python3 online submissions for Valid Parentheses.
Memory Usage: 13.3 MB, less than 5.22% of Python3 online submissions for Valid Parentheses.
Code & C++
class Solution {
public:
bool isValid(string s) {
int len = s.size();
if (len==0)return true;
stack<char> tmp;
string left="({[";
map<char,char> mapping = {{')','('},{']','['},{'}','{'}};
for(int i=0;i<len;++i){
if(left.find(s[i])!=string::npos){
tmp.push(s[i]);
}else{
char ch = mapping[s[i]];
if(tmp.empty()){
return false;
}
if(ch == tmp.top()){
tmp.pop();
}else{
return false;
}
}
}
if(tmp.empty()) return true;
return false;
}
};
结果:
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Valid Parentheses.
Memory Usage: 9.1 MB, less than 14.29% of C++ online submissions for Valid Parentheses.