ACM括号配对问题 Java

描述

现在,有一行括号序列,请你检查这行括号是否配对。

输入

第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[", "]", "(", ")" 四种字符

输出

每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No

样例输入

3
[(])
(])
([[]()])

样例输出

No
No
Yes

第一种方法用栈 自己运行没问题   但在ACM上编译出错

import java.util.Scanner;
import java.util.Stack;
 
/**
 * @author Owner
 * 
 */
public class Two {
 
	@SuppressWarnings("resource")
	public static void main(String[] args) {
	
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();//测试的数据个数
		
		Stack<Character> stack = null;
		
		while(n!=0){
			String str = sc.next();
			
			//字符为奇数
			if(str.length()%2==1){ 
				System.out.printf("No");
				System.out.print("\n");
			}else{
				
				//字符为偶数
				stack = new Stack<Character>();
				
				//遍历测试字符串
				for(int i=0;i<str.length();i++){
					if(stack.isEmpty()){
						stack.push(str.charAt(i));
					}else if(stack.peek()=='[' && str.charAt(i)==']' || stack.peek()=='(' && str.charAt(i)==')'){
						stack.pop();
					}else{
						stack.push(str.charAt(i));
					}
				}
				
				System.out.printf(stack.isEmpty() ? "Yes" : "No");
				System.out.print("\n");
			}
			
		}
	}
}

第二种方法提交成功

import java.util.Scanner;
import java.util.Stack;

public class Main {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int N = scanner.nextInt();
		String s;
		for (int i = 0; i < N; i++) {
			s = scanner.next();
			if (pan.isMatch(s)) {
				System.out.print("Yes");
				System.out.print("\n");
			} else {
				System.out.print("No");
				System.out.print("\n");
			}
		}

	}
}

class pan {

	public static boolean isMatch(String s) {
		Stack<Character> sk = new Stack<Character>();
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) == '(') {
				sk.push('(');
			}
			if (s.charAt(i) == ')') {
				if (!sk.isEmpty() && sk.pop() == '(')
					continue;
				else
					return false;
			}
			if (s.charAt(i) == '[') {
				sk.push('[');
			}
			if (s.charAt(i) == ']') {
				if (!sk.isEmpty() && sk.pop() == '[')
					continue;
				else
					return false;
			}
		}
		if (sk.isEmpty())
			return true;
		else
			return false;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39212193/article/details/81700058