Java O(N) solution!


  • 0
    T
    class Solution {
        public boolean checkValidString(String s) {
            int rmL=0;
            int rmR=0;
            char[] array = s.toCharArray();
            int index = -1;
            for(int i=0;i<array.length;i++){
                if(array[i]=='('){
                    rmL++;
                }else if(array[i]==')'){
                    if(rmL==0){
                        rmR++;
                        index = i;
                    }else{
                        rmL--;
                    }
                }
            }
            int countLeftStar=0;
            int count = 0;
            for(int i=0;i<=index;i++){
                if(array[i]=='*'){
                    countLeftStar++;
                }else if(array[i]=='('){
                    count--;
                }else if(array[i]==')'){
                    count++;
                    if(count>0&&countLeftStar<count){
                        return false;
                    }
                }
            }
            
            int countRightStar=0;
            count = 0;
            for(int i=s.length()-1;i>index;i--){
                if(array[i]=='*'){
                    countRightStar++;
                }else if(array[i]==')'){
                    count--;
                }else if(array[i]=='('){
                    count++;
                    if(count>0&&countRightStar<count){
                        return false;
                    }
                }
            }
            return true;
        }
    }
    
    

Log in to reply
 

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