1.3.4 编写一个Stack的用例Parentheses,从标准输入读取一个文本流并使用栈判定其中的括号是否配对完整。例如,对于[()]{}{[()()]()} 程序应该打印true,对于 [(])则打印false。
import java.util.*;
/**
*@author:wjy329
*charAt()返回指定索引处的字符;方便进行判断。({[ 入栈操作,当为)}]时,则出栈并判断出栈的字符是否与其匹配,匹配则真,继续判断,否则返回false,结束程序。
*/
public class panduanPipei{
public static boolean fun(String myStr){
Stack<Character> stack = new Stack<Character>();
for(int i=0;i<myStr.length();i++)
{
if(myStr.charAt(i) == '(')
stack.push('(');
if(myStr.charAt(i) == '{')
stack.push('{');
if(myStr.charAt(i) == '[')
stack.push('[');
if(myStr.charAt(i) == ')'){
if(stack.isEmpty())
return false;
if(stack.pop() != '(')
return false;
}
else if(myStr.charAt(i) == '}'){
if(stack.isEmpty())
return false;
if(stack.pop() != '{')
return false;
}
else if(myStr.charAt(i) == ']'){
if(stack.isEmpty())
return false;
if(stack.pop() != '[')
return false;
}
}
return stack.isEmpty();
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println(fun(s));
}
}
运行结果: