标签:
描述:
现在,有一行括号序列,请你检查这行括号是否配对。
3 [(]) (]) ([[]()])
No No Yes
import java.util.Scanner; public class No2 { private String checkout(String str) { try { StringBuffer asb = new StringBuffer(str); // 模拟栈A StringBuffer bsb = new StringBuffer(); // 模拟栈B int length = asb.length(); while (length > 0) { // 遇右括号,移A入B if (asb.charAt(length - 1) == ‘)‘ || asb.charAt(length - 1) == ‘]‘) { bsb.append(asb.charAt(length - 1)); asb.deleteCharAt(length - 1); length = asb.length(); continue; } // 遇左括号,若无法与B中栈顶元素合法匹配,则序列非法;若合法匹配,移A移B if (asb.charAt(length - 1) == ‘(‘) { if (bsb.charAt(bsb.length() - 1) != ‘)‘) { return "No"; } else { asb.deleteCharAt(asb.length() - 1); bsb.deleteCharAt(bsb.length() - 1); length = asb.length(); continue; } } if (asb.charAt(length - 1) == ‘[‘) { if (bsb.charAt(bsb.length() - 1) != ‘]‘) { return "No"; } else { asb.deleteCharAt(asb.length() - 1); bsb.deleteCharAt(bsb.length() - 1); length = asb.length(); continue; } } } if (bsb.length() == 0) { return "Yes"; } } catch (RuntimeException e) { } return "No"; } public static void main(String args[]) throws Exception { try { Scanner cin = new Scanner(System.in); int num = cin.nextInt(); String[] result = new String[num]; No2 no2 = new No2(); for (int i = 0; i < num; i++) { String str = cin.next(); result[i] = no2.checkout(str); } for (int i = 0; i < num; i++) { System.out.println(result[i]); } } catch (RuntimeException e) { } } }
标签:
原文地址:http://www.cnblogs.com/lifelonglearner/p/4611466.html