括号匹配问题

判断字符串中的括号是否匹配。

package com.huawei.scp.util;

import java.util.Stack;

public class ParenthesisMatching
{

    public boolean check(String str)
    {
        Stack<Character> stack = new Stack<Character>();
        boolean flag = true;
        for (int i = 0; i < str.length() && flag; i++)
        {
            try
            {
                switch (str.charAt(i))
                {
                case '(':
                case '[':
                case '{':
                    stack.push(str.charAt(i));
                    break;
                case ')':
                    if (stack.pop() != '(')
                        flag = false;
                    break;
                case ']':
                    if (stack.pop() != '[')
                        flag = false;
                    break;
                case '}':
                    if (stack.pop() != '{')
                        flag = false;
                    break;
                }
            }
            catch (Exception e)
            {
                flag = false;
            }
        }
        if (flag && !stack.isEmpty())
            flag = false;

        return flag;
    }

    public static void main(String[] args)
    {
        ParenthesisMatching pm = new ParenthesisMatching();
        System.out.println("(: " + pm.check("("));
        System.out.println("a(bc[d])e{fd}: " + pm.check("a(bc[d])e{fd}"));
        System.out.println("a(bc]d: " + pm.check("a(bc]d"));
        System.out.println("a(b(c)d: " + pm.check("a(b(c)d"));
        System.out.println("a(b)c)d: " + pm.check("a(b)c)d"));
    }
}


你可能感兴趣的:(括号匹配问题)