zoukankan      html  css  js  c++  java
  • 判断字符串括号是否合法-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);
        }
    }
  • 相关阅读:
    1052 卖个萌 (20 分)
    1046 划拳 (15 分)
    1051 复数乘法 (15 分)
    1042 字符统计 (20 分)哈希
    1041 考试座位号 (15 分)哈希
    1061 判断题 (15 分)
    1093 字符串A+B (20 分)简单哈希
    Hibernate框架
    SVN的安装与介绍
    easyUI的简单操作
  • 原文地址:https://www.cnblogs.com/goodtest2018/p/14773995.html
Copyright © 2011-2022 走看看