判断字符串括号是否合法-2

例 1:判断字符串括号是否合法

题目】字符串中只有字符'('和')'。合法字符串需要括号可以配对。比如:

输入:"()"

输出:true

解释:(),()(),(())是合法的。)(,()(,(()是非法的。

 

package leetcode;

public class StackSolution2 {
    public boolean isValid(String s){
        // 当字符串本来就是空的时候,我们可以快速返回true
        if(s ==null || s.length() == 0 ){
            return true;
        }
        // 当字符串长度为奇数的时候,不可能是一个有效的合法字符串
        if(s.length() % 2 == 1){
            return false ;
        }
        // 消除法的主要核心逻辑:
        int leftBraceNumber = 0 ;
        for(int i = 0 ; i  <s.length(); i++){
            // 取出字符
            char c = s.charAt(i);
            // 如果是'(',那么压栈
            if(c == '('){
                leftBraceNumber++;
            }else if(c == ')'){
                // 如果是')',那么就尝试弹栈
                if(leftBraceNumber<=0){
                    // 如果弹栈失败,那么返回false
                    return false;
                }
                --leftBraceNumber;
            }
        }
        return  leftBraceNumber==0;
    }
    public static void main(String[] args){
        StackSolution2 stackSolution2 = new StackSolution2();
        boolean  b= stackSolution2.isValid("()()()");
        boolean  c= stackSolution2.isValid("((()))()(())(()())");
        System.out.println(b);
        System.out.println(c);
    }
}

 

posted on 2021-05-16 16:07  凌晨三点半的飞机  阅读(216)  评论(0编辑  收藏  举报