package algorithm;
import java.util.Stack;
/*
原题
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.
题目大意
给定一个只包含(‘, ‘)’, ‘{‘, ‘}’, ‘[’ 和‘]’的字符串,验证它是否是有效的。括号必须配对,并且要以正确的顺序。
* */
public class ValidParentheses {
public static boolean parentheses(String para){
if(para==null){
return true;
}
//使用栈先进后出
Stack<Character> stack=new Stack<Character>();
int length=para.length();
for(int i=0;i<length;i++){
char tmpCh=para.charAt(i);
switch(tmpCh){
case '(':{
}
case '{':{
}
case '[':{
stack.push(tmpCh);
break;
}
case ')':{
char ch=stack.pop();
if(ch!='(')
return false;
break;
}
case ']':{
char ch=stack.pop();
if(ch!='[')
return false;
break;
}
case '}':{
char ch=stack.pop();
if(ch!='{'){
System.out.println("此时stack为:"+stack);
return false;
}
break;
}
}
}
System.out.println("此时stack为:"+stack);
if(stack.isEmpty()){
return true;
}
return false;
}
/*
private static Stack printCharacters(String para) {
if(para==null){
return null;
}
//使用栈先进后出
Stack<Character> stack=new Stack<Character>();
int length=para.length();
for(int i=0;i<length;i++){
char tmpCh=para.charAt(i);
switch(tmpCh){
case '(':{
}
case '{':{
}
case '[':{
stack.push(tmpCh);
break;
}
case ')':{
}
case ']':{
}
case '}':{
char ch=stack.pop();
break;
}
}
}
return stack;
}
*/
public static void main(String[] args) {
String para="()[]{}";
boolean flag=parentheses(para);
if(flag){
System.out.println(para+"匹配");
}else{
System.out.println(para+"不匹配");
}
// Stack<Character> tmpStack=printCharacters(para);
//System.out.println(tmpStack);
}
}