输入格式如下:
3
{[()]}
{[(])}
{{[[(())]]}}
输出格式如下:
YES
NO
YES
算法描述: 利用栈来判断(注意出栈时,考虑栈是否为空;最后匹配的结果应该是栈为空)
1)从左到右进行扫描字符
2)若为左括号‘(’‘[’‘{’,则进栈
3)若为右括号。判断当前栈是否为空
a)是,括号不匹配,结束
b)否,判断当前括号和栈顶括号是否匹配,若匹配,栈顶元素出栈,继续1),否则不匹配,结束
4)最后扫描结束,判断栈是否为空,若为空,则匹配,否则不匹配。
实现代码如下:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public boolean isEqual(char top ,char ch){
if((top=='('&&ch==')') ||(top=='['&&ch==']') ||(top=='{'&&ch=='}')) {
return true;
}else{
return false;
}
}
public boolean isBalanced(String str){
boolean flag = true;
Stack<Character> stack = new Stack<Character>();//create an empty stack
for(int i=0 ;i<str.length();i++){
if(str.charAt(i)=='(' || str.charAt(i)=='[' || str.charAt(i)=='{'){
stack.push(str.charAt(i));
}else{
//check the top element with the current character
if(stack.empty()==true){
flag = false;
break;
}else{
if(isEqual(stack.peek(),str.charAt(i))){
stack.pop();
}else{
flag = false;
break;
}
}
}
}//end for
if(stack.empty()== false){
flag = false;
}
return flag;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine();
String str = "";
for(int i=0 ; i<t ;i++){
str = sc.nextLine();
//System.out.println(str);
Solution obj = new Solution();
if(obj.isBalanced(str)==true){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
}
这里我又犯了一个错误,那就是,首先scanner对象通过nextInt()接收一个整数,后面依次接收字符串时候,我直接用了nextLine()导致输出有误,因为 整数后面的\n会被nextLine()接收。所以要在接收字符串之前调用一次nextLine()。其实这里最好用next()。关于next()和nextLine()的区别,请参考之前的文章http://blog.csdn.net/fffllllll/article/details/51615204