爱程序网

括号配对问题

来源: 阅读:

描述:

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

输入:
第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
输出:
每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
样例输入:
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) {

        }
    }
}

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助