题目:https://leetcode.com/problems/valid-parentheses/description/
题目
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
思路
需要后进先出来做匹配,用栈非常合适。
class Solution {
public:
bool isValid(string s) {
std::stack<char> chstack;
for(int i = 0 ;i<s.length();i++){
if(s[i]=='('||s[i]=='{'||s[i]=='[') chstack.push(s[i]);
else{
if(chstack.empty()) return false;
char chtmp = chstack.top();
chstack.pop();
switch(chtmp){
case '(':{
if(s[i]==')') continue;
else return false;
break;
}
case '{':{
if(s[i]=='}') continue;
else return false;
break;
}
case '[':{
if(s[i]==']') continue;
else return false;
break;
}
}
}
}
if(!chstack.empty()) return false;
return true;
}
};
1.栈的使用
声明:std::stack<char> stack;
操作:添加 stack.push();是否为空stack.empty();取top:stack.top();删除top:stack.pop();
2.switch-case
switch(char){
case 'a':{
cout<<char<<endl;
break;
}
}
JAVA
class Solution {
public boolean isValid(String s) {
Stack<Character> chstack = new Stack<Character>();
for(char c : s.toCharArray()){
if(c=='(') chstack.push(')');
else if(c=='{') chstack.push('}');
else if(c=='[') chstack.push(']');
else if(chstack.isEmpty()||chstack.pop()!=c) return false;
}
return chstack.isEmpty();
}
}
语法:
1.栈的使用:
声明:
Stack<Character> chstack = new Stack<Character>();
其中<>中应为对象,而char为内置数据类型,所以需要使用 Character 类型,可以和char 用'=='比较,用'='赋值。
操作:
添加:chstack.push();
取top并删除:chstack.pop();
class Solution {
public boolean isValid(String s) {
Stack<Character> chstack = new Stack<Character>();
for(char c : s.toCharArray()){
switch(c){
case '(':
chstack.push(')');
break;
case '{':
chstack.push('}');
break;
case '[':
chstack.push(']');
break;
default:
if(chstack.isEmpty()||chstack.pop()!=c) return false;
}
}
return chstack.isEmpty();
}
}
语法:
2.switch-case
switch(c){
case '{':
case '{':
pass;
break;
default:
pass;
break;
}