Leetcode 20 有效的括号
题目描述
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
来源:力扣(LeetCode)题目链接
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解1(map+栈)
class Solution {
public:
bool isValid(string s) {
int len = s.size();
if((len & 1) == 1) return false;
//右括号作为索引,只是负责快速查找对应的左括号
unordered_map<char, char> hash = {
{')', '('},
{']', '['},
{'}', '{'}
};
stack<char> cur;
for(int i = 0; i < len; i++){
if(hash.count(s[i])){
//这里注意,如果栈空还遇到了右括号,则说明不合理
//这里也可以换成ASCII码来判断是不是左右配对
if(cur.empty() || cur.top() != hash[s[i]]){
return false;
}
cur.pop();
}else{
cur.push(s[i]);
}
}
return cur.empty();
}
};
另一种
class Solution {
map<char, char> sysmap = {
{'(', ')'},
{'{', '}'},
{'[', ']'}
};
public:
bool isValid(string s) {
stack<char> stk;
int i = 0;
while(i < s.size()){
if(s[i] == '(' || s[i] == '[' || s[i] == '{'){
stk.push(s[i]);
}
else{
if(stk.size() && sysmap[stk.top()] == s[i])
stk.pop();
else
return false;
}
i ++;
}
return stk.empty();
}
};
题解2(ASCII码值+栈)
class Solution {
public:
bool isValid(string s) {
// 常数优化:空字符串+奇数长度
if(s.empty() || s.size()%2) return false;
// 找到成对的括号之间的关系: ASCII码值
// 根据匹配括号的机制想到弹栈(先进后出):一直先匹配的是邻近的括号
stack<char> temp;
for(auto c : s){
if(temp.empty()){
temp.push(c);
}else{
char t = temp.top();
temp.pop();
if(1==c-t || 2==c-t){
continue;
}else {
temp.push(t);
temp.push(c);
}
}
}
return temp.empty();
}
};