括号配对问题JAVA实现

1. 括号匹配的四种可能性:
①左右括号配对次序不正确
②右括号多于左括号
③左括号多于右括号
④左右括号匹配正确

2. 算法思想:
1.顺序扫描算数表达式(表现为一个字符串),当遇到三种类型的左括号时候让该括号进栈;
2.当扫描到某一种类型的右括号时,比较当前栈顶元素是否与之匹配,若匹配,退栈继续判断;
3.若当前栈顶元素与当前扫描的括号不匹配,则左右括号配对次序不正确,匹配失败,直接退出;
4.若字符串当前为某种类型的右括号而堆栈已经空,则右括号多于左括号,匹配失败,直接退出;
5.字符串循环扫描结束时,若堆栈非空(即堆栈尚有某种类型的左括号),则说明左括号多于右括号,匹配失败;

6.正常结束则括号匹配正确。

package N2;
import java.util.*;

public class Test2 {
	public static void main(String[] args) throws Exception {
		Scanner input = new Scanner(System.in);
		int num = input.nextInt();
		String[] str = new String[num];
		for (int i = 0; i < num; i++) {
			str[i] = input.next();
		}
		
		for (int i = 0; i < num; i++) {
			if (matchInfo(str[i]) == true)
				System.out.println("YES\n");
			else
				System.out.println("NO\n");
		}

	}

	 public static boolean matchInfo(String str)
	 {
	        Stack stack = new Stack(); 
	        char[] ca = str.toCharArray();
	        if(((Character) ca[0]) == '[' || ((Character) ca[0]) == '(')
	        {
			        for (int index = 0; index < str.length(); index++)
			        {
			        	Character c1 = (Character) ca[index];
			        	if((c1 == '(') || (c1 == '['))
			        	{  
			        		stack.push(c1);
			        	}
			        	else if (stack.empty()==true)
			        	{
			        		return false;
			        	}
			        	else if((c1 == ')') || (c1 == ']'))
			        	{
			        		if(((((Character) stack.peek()) == '(')&& (c1 == ')'))||((((Character) stack.peek()) == '[')&& (c1 == ']')))
			        				{
			        			      stack.pop();
			        				}
			        		else return false;
			        	}
			        	
			        	
			        }
			    
			        return stack.empty();
	        }   
	        else return false;
	    }
	
}

    原文作者:括号匹配问题
    原文地址: https://blog.csdn.net/hongkangwl/article/details/12678717
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞