题目:20. 有效的括号
思路:栈的基础题,时间复杂度0(n)
C++版本:
class Solution {
public:
bool isValid(string s) {
stack<char> st;
st.push('#');//哨兵,以防越界
bool flag=true;
for(char c:s){
if(c=='('|| c=='['|| c=='{'){
st.push(c);
}else {
if(c==')'&&st.top()=='(' || c==']'&&st.top()=='[' ||c=='}'&&st.top()=='{' ){
st.pop();
}else{
flag=false;
break;
}
}
}
if(st.size()>1) flag=false;
return flag;
}
};
JAVA版本:
class Solution {
public boolean isValid(String s) {
Stack<Character> st=new Stack<>();
st.push('#');
boolean flag=true;
for(char c:s.toCharArray()){
if(c=='('|| c=='['|| c=='{'){
st.push(c);
}else {
if(c==')'&&st.peek()=='(' || c==']'&&st.peek()=='[' ||c=='}'&&st.peek()=='{' ){
st.pop();
}else{
flag=false;
break;
}
}
}
if(st.size()>1) flag=false;
return flag;
}
}