字符串问题之 括号字符串的有效性和最长有效长度

给定一个字符串 str, 判断是不是整体有效的括号字符串

str=“(())”    true

str=“()a()”  false

进阶题目:  给定一个括号字符串str,返回最长的有效括号子串

首先原问题的解决思路:

各种判断:

  遍历判断每个字符是不是“(” 或“)”,如果不是,false

  遍历到每一个字符时,都检查到目前为止“(” 和“)”的数量, 如果“)”多 返回false

  便利后检查“(” 和 “)”的数量一样多 true  否则false

package TT;

public class Test6 {
  
    public static boolean isValid(String str){
        
        if(str==null || str.equals("")){
            return false;
        }
        
        char[] chas = str.toCharArray();
        int status = 0;
        for(int i =0; i<chas.length; i++){
            if(chas[i] !=')' && chas[i] !='('){
                return false;
                }
            if(chas[i] ==')' && --status <0){
                return false;
            }
            if(chas[i] == '('){
                 status++;
            }
        }
        return status == 0;
    }
    
    
    public static void main(String[] args){
        
         String b ="(())";
         
         boolean c = isValid(b);
        
         System.out.println(c);
    }
    
    
    
}

结果:

public class Test7 {
    public static boolean isValid(String str) {

        int countRight = 0;
        int countLeft = 0;
        for (int i = 0; i < str.length(); i++) {
            char now = str.charAt(i);
               
             if (now !='(' && now !=')') {
                return false;
            }
            
                if (now == '(') {
                    countLeft++;
                } else if (now == ')') {
                    countRight++;
                    if (countRight > countLeft) {
                        return false;
                    }

                }
        }
        if (countRight == countLeft) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {

        String b = "()()";
        boolean c = isValid(b);
        System.out.println(c);

    }
}
原文地址:https://www.cnblogs.com/toov5/p/7410328.html