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


  • 0
    S

    public boolean detectCapitalUse(String word) {
    if(word == null || word.length() <= 1) return true;

        boolean flag = false;
        if(word.charAt(0) >= 'A' && word.charAt(0) <= 'Z') flag = true;
        if(word.charAt(1) >= 'A' && word.charAt(1) <= 'Z') {
            if(!flag) return false; 
        } else {
            flag = false;
        }
        
        for(int i=2; i<word.length(); i++) {
            if(word.charAt(i) >= 'A' && word.charAt(i) <= 'Z') {
                if(!flag) return false;
            } else {
                if(flag) return false;
            }
        }
        
        return true;
    }

Log in to reply
 

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