括号匹配

题目描述

检查字符串中方括号、圆括号和花括号是否配对

输入

每个字符串一行,以0表示输入结束

输出

true 或者 false 每个一行

样例输入

(12,11,44,[6,[9]),(#)
([#],([2],3,1}
([#],([2],3,1),7)
0

样例输出

false
false
true

代码实现
import java.util.Scanner;
import java.util.Stack;
public class Bracket {
	Stack<String> result=new Stack<String>();
	Stack<String> result1=new Stack<String>();
	public Bracket(){
		Scanner sc=new Scanner(System.in);
		String infix;
		while(!"0".equals(infix = sc.nextLine())){
		Stack<String> stack=new SeqStack<String>(infix.length());
		
		
		for(int i=0;i<infix.length();i++){
			char ch=infix.charAt(i);
			switch(ch){
			case'(':
				stack.push(ch+"");
				break;
			case')':
				if(!stack.isEmpty()&&stack.peek().equals("("))
					stack.pop();
				else
					stack.push(ch+"");
				break;
			case'[':
				stack.push(ch+"");
				break;
			case']':
				if(!stack.isEmpty()&&stack.peek().equals("["))
					stack.pop();
				else
					stack.push(ch+"");
				break;
			case'{':
				stack.push(ch+"");
				break;
			case'}':
				if(!stack.isEmpty()&&stack.peek().equals("{"))
					stack.pop();
				else
					stack.push(ch+"");
				break;
			}
		}
		if(stack.isEmpty())
			result.push("true");
		else
			result.push("false");
		}
		while(!result.isEmpty()){
			result1.push(result.peek());
			result.pop();
		}
		while(!result1.isEmpty()){
		System.out.println(result1.peek());
		result1.pop();
		}
	}
	public static void main(String args[]){
		Bracket b=new Bracket();
	}
}
class SeqStack<T> extends Stack<String> {
	public SeqStack(int length) {
		// TODO Auto-generated constructor stub
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

callmeCassie

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值