Use stack but more usefule,show codes!


  • 0
    C
    public boolean isValid(String s) {
                if (s == null || "".equals(s)) {
                    return false;
                }
                if (s.length() % 2 != 0) {
                    return false;
                } else {
                    Stack<Character> stack = new Stack<Character>();
                    for (int i = 0; i < s.length(); i++) {
                        char c1 = s.charAt(i);
                        if(!stack.isEmpty()){
                            char s1 = stack.peek();
                            if(c1 - s1 >0 && c1 - s1 < 3){
                                stack.pop();
                            }else{
                                stack.push(c1);
                            }
                        }else{
                            stack.push(c1);
                        }
                    }
                    return stack.isEmpty();
                }
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.