您的位置:首页 > 其它

利用栈判断括号是否匹配

2016-06-18 15:59 369 查看
输入格式如下:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: