利用栈判断括号是否匹配

输入格式如下:
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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值