Using state machine. (Java, O(n))


  • 0
    T

    public class Solution {

    private static boolean isCap(Character ch){
        if(ch>='A' && ch<='Z')
            return true;
        else
            return false;
    }
    
    public boolean detectCapitalUse(String word) {
        if(word==null || word.length()<=1)
            return true;
        /*
        state=0, all caps
        state=1, all small
        state=2, first cap, rest small
        state=3, any invalid state
        */
        int state=0;
        if(isCap(word.charAt(0)) && isCap(word.charAt(1))){
            state=0;
        } 
        else if(!isCap(word.charAt(0)) && !isCap(word.charAt(1))){
            state=1;
        }
        else if(isCap(word.charAt(0)) && !isCap(word.charAt(1))){
            state=2;
        }
        else if(!isCap(word.charAt(0)) && isCap(word.charAt(1))){
            state=3;
            return false;
        }
        
        for(int i=2;i<word.length();i++){
            if(state==0 && !isCap(word.charAt(i))){
                state=3; return false;
            }
            else if(state==1 && isCap(word.charAt(i))){
                state=3; return false;
            }
            else if(state==2 && isCap(word.charAt(i))){
                state=3; return false;
            }
            else {
                continue;
            }
        }//end of for loop
        return true;
    }
    

    }


Log in to reply
 

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