左括号入栈,然后pop栈,看看是否和下一位char配套

public boolean isValid(String s) {

    if(s.length()==0||s==null)

    return false;

    char[] x = s.toCharArray();

    Stack<Character> stk = new Stack<Character>();

    for(int i=0;i<x.length;i++){

            if(x[i]=='(' || x[i]=='{' || x[i]=='['){

            stk.push(x[i]);

            }

            else{

                if(stk.size()==0)

                return false;

                char top = stk.pop();

                 if(x[i]==')' && top!='('){

                    return false;

                }

                if(x[i]==']' && top!='['){

                    return false;

                }

                if(x[i]=='}' && top!='{'){

                    return false;

                }
            }
    }

    return stk.size()==0;

}

results matching ""

    No results matching ""