Letter Counting Solution, O(n)


  • 0
    J
        public boolean detectCapitalUse(String word) {
            int numCaps = 0;
            for (char c : word.toCharArray()) if (isCapital(c)) numCaps++;
            return ( numCaps==word.length() || ( numCaps==1 && isCapital(word.charAt(0)) ) || numCaps==0);
        }
        private boolean isCapital(char c) {
            return ( 'A' <= c && c <= 'Z');
        }
    

    Runs off the idea that a valid string has (1) either no capital letters, (2) only one capital (the first), or (3) all capital letters.

    Simply count them out and check if it falls in to any of those


Log in to reply
 

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