算法 第四版 1.3.4 习题解答 判断括号是否配对完整

 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));
	}
}

运行结果:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值