判断括号是否匹配的java方法

验证需要判断一个字符串里括号是否成对出现,发现正则满足不了,只能用java方法,网上找了下,没有合适的,自己参考简单的例子改造了个,希望对大家有用。

public class ValidatorMethod
{
  public boolean isMatch(String s)
  {
        Stack<Character> sc=new Stack<Character>();
        char[] c=s.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i]=='('||c[i]=='['||c[i]=='{') {
                sc.push(c[i]);
            }
            else if (c[i]==')') {
            if(sc.isEmpty()){
                    return false;
            }
            else{
                if (sc.peek()=='(') {
                        sc.pop();
                    }
            }
            }
            else if (c[i]==']') {
            if(sc.isEmpty()){
                    return false;
            }
            else
            {
            if (sc.peek()=='[') {
                     sc.pop();
                }
            }
            }else if (c[i]=='}') {
            if(sc.isEmpty()){
                    return false;
            }
            else{
                    if (sc.peek()=='{') {
                        sc.pop();
                    }
            }
            }
        }
        if (sc.empty()) {
            return true;
        }else {
            return false;
        }
    }

    public static void main(String args[])
    {
    ValidatorMethod validatorMethod = new ValidatorMethod();
    String str="(((520+480)*38/10)/2*((520+480)*38/10)/2)";
    boolean bool=validatorMethod.isMatch(str);
    System.out.println(bool);
   
    }
}

你可能感兴趣的:(java)