leetcode刷题之20. 有效的括号
题目
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
示例:
输入:s = "()[]{}"
输出:true
提示:
1 <= s.length <= 104
s 仅由括号 ‘()[]{}’ 组成
我的代码
思路:经典的栈的应用。
从左到右依次扫描字符串,遇到左括号入栈,遇到右括号时检查是否与栈顶元素匹配。若栈顶的左括号与右括号匹配则弹出这一对括号。遍历完成后若栈空,表示字符串有效返回true。
注意:在取栈顶元素之前检查栈是否为空。
每次取栈顶都是在遇到右括号时,若栈空表示右括号的左边没有括号,肯定不符合要求,直接返回false。
class Solution {
public:
bool isValid(string s) {
//1.有名又经典 的 栈的应用
stack<char> st;
st.push(s[0]);
for(int i=1; i<s.length(); i++){
if(s[i]=='(' || s[i]=='[' || s[i]=='{'){
st.push(s[i]);
continue;
}
if(s[i]==')'){
if(!st.empty() && st.top()=='('){
st.pop();
continue;
}else return false;
}if(s[i]==']')
if(!st.empty() && st.top()=='['){
st.pop();
continue;
}else return false;
if(s[i]=='}')
if(!st.empty() && st.top()=='{'){
st.pop();
continue;
}else return false;
}
if(st.empty()) return true;
else return false;
}
};
代码优化
(代码写出来后很重复繁杂,感觉可以简化)
- 字符长度奇数,直接返回false
- 括号配对用数组表示
- C++遍历可以使用冒号
class Solution {
public:
bool isValid(string s) {
//有名又经典 的 栈的应用
if(s.length()&1==1) return false;
stack<char> st;
st.push(s[0]);
for(int i=1;i<s.length();i++){
//左括号入栈
if(s[i]=='(' || s[i]=='[' || s[i]=='{'){
st.push(s[i]);
continue;
}
//右括号先判断栈空
if(st.empty()) return false;
char tmp=st.top();
if(s[i]==')' && tmp=='(' ||s[i]==']' && tmp=='['||s[i]=='}' && tmp=='{')
st.pop();
else
return false;
}
if(st.empty()) return true;
else return false;
}
};