PTA符号配对


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

public class Main {

	private static final char LEFT_XIAO = '(';
	private static final char RIGFHT_XIAO = ')';
	private static final char LEFT_HUA = '{';
	private static final char RIGHT_HUA = '}';
	private static final char LEFT_FANG = '[';
	private static final char RIGHT_FANG = ']';
	static Stack<Character> stack = new Stack<Character>();
	private static String s;
	private static boolean leftFlag = true;
	private static boolean rightFlag = true;
	private static String rightChar = "";

	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		while (cin.hasNext()) {
			s = cin.nextLine();
			isBalance();
			if (leftFlag && rightFlag)
				;
			else
				break;
			if (s.equals("."))
				break;
		}
		cin.close();
		if (!stack.isEmpty()) {
			char cc = stack.pop();
			System.out.println("NO");
			if (cc == LEFT_XIAO || cc == LEFT_HUA || cc == LEFT_FANG) {
				System.out.println(cc + "-?");
			} else if (cc == '<') {
				System.out.println("/*-?");
			}
			leftFlag = false;
			rightFlag = false;
		}
		if (leftFlag && rightFlag) {
			System.out.println("YES");
		} else if (rightFlag) {
			System.out.println("NO");
			System.out.println("?-" + rightChar);
		} else if (leftFlag) {
			System.out.println("NO");
			System.out.println((stack.peek() == '<' ? "/*" : stack.pop()) + "-?");
		}
	}

	public static void isBalance() {
		int len = s.length();
		for (int i = 0; i < len; ++i) {
			char c = s.charAt(i);
			if (c == LEFT_XIAO || c == LEFT_HUA || c == LEFT_FANG) {
				stack.push(c);
			} else if (c == '/' && i + 1 < len && s.charAt(i + 1) == '*') {
				stack.push('<');
				++i;
			} else {
				if (c == RIGFHT_XIAO || c == RIGHT_HUA || c == RIGHT_FANG) {
					if (stack.isEmpty()) {
						leftFlag = false;
						rightChar += c;
						return;
					}
					if ((c == RIGFHT_XIAO && stack.peek() != LEFT_XIAO)
							|| (c == RIGHT_HUA && stack.peek() != LEFT_HUA)
							|| (c == RIGHT_FANG && stack.peek() != LEFT_FANG)
							) {
						rightFlag = false;
						return;
					}
					stack.pop();
				} else if (c == '*' && i + 1 < len && s.charAt(i + 1) == '/') {
					if (stack.isEmpty()) {
						leftFlag = false;
						rightChar = "*/";
						return;
					}
					if (stack.peek() != '<') {
						rightFlag = false;
						return;
					}
					stack.pop();
					++i;// 这里容易忘,不然 用例/*/**/*/过不去(最后一个测试点)
				}
			}
		}
	}
}
========================================Talk is cheap, show me the code=======================================


posted @ 2018-02-27 15:05  绿叶萌飞  阅读(430)  评论(0编辑  收藏  举报