码迷,mamicode.com
首页 > 其他好文 > 详细

括号配对问题

时间:2015-06-30 21:42:01      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

描述:

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

输入:
第一行输入一个数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) {

        }
    }
}

 

括号配对问题

标签:

原文地址:http://www.cnblogs.com/lifelonglearner/p/4611466.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!