Java - O(n) time and O(1) space solution


  • 3
    C

    Does not use the string.match method, but rather iterates through the String until it hits the conditions for it to return a FALSE.

    Any feedback is appreciated!

    public boolean checkRecord(String s) {
            //Time ~ O(n)
            //Space ~ O(1)
            // ---> where n is the length of String s
            
            int countA = 0;
            int countL = 0;
            
            for(int i = 0; i < s.length(); i++){
                if(s.charAt(i) == 'A'){
                    if(countA == 1){
                        return false;
                    } else{
                        countA = countA + 1;
                    }
                    countL = 0;
                } else if(s.charAt(i) == 'L'){
                    if(countL == 2){
                        return false;
                    } else{
                        countL = countL + 1;
                    }
                } else{
                    countL = 0;
                }
            }
            
            return true;
        }
    

Log in to reply
 

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