Simple Java Solution O(n) time O(1) space


  • 21
        public boolean detectCapitalUse(String word) {
            return word.equals(word.toUpperCase()) || 
                   word.equals(word.toLowerCase()) ||
                   Character.isUpperCase(word.charAt(0)) && 
                   word.substring(1).equals(word.substring(1).toLowerCase());
        }
    

    A slightly more verbose, but more efficient solution:

        public boolean detectCapitalUse(String word) {
            int numUpper = 0;
            for (int i=0;i<word.length();i++)
                if (Character.isUpperCase(word.charAt(i))) numUpper++;
            if (numUpper == 1) return Character.isUpperCase(word.charAt(0));
            return numUpper == 0 || numUpper == word.length();
        }
    
    

  • 0

    Like your first solution, very concise! Thanks!


  • 0

    @compton_scatter Sweet. This is what I got (beats 96% on the OJ for now):

        public boolean detectCapitalUse(String word) {
            if (word.isEmpty()) return true;
            boolean firstLetterCap = Character.isUpperCase(word.charAt(0));
            String substr = word.substring(1);
            if (!firstLetterCap) {
                return allCharsLower(substr);
            } else {
                return allCharsUpper(substr) || allCharsLower(substr);
            }
        }
        
        private boolean allCharsLower(String s) {
            for(int i = 0; i < s.length(); i++) {
                if (Character.isUpperCase(s.charAt(i))) return false;
            }
            return true;
        }
        
        private boolean allCharsUpper(String s) {
            for(int i = 0; i < s.length(); i++) {
                if (Character.isLowerCase(s.charAt(i))) return false;
            }
            return true;
        }
    

  • 0
    G

    @compton_scatter You can simplify it,this is my code:

        public boolean detectCapitalUse(String word) {
           return word.substring(1).equals(word.substring(1).toLowerCase())||word.equals(word.toUpperCase());
           }
    

  • 0
    R

    Just so it's clear, your first solution is not O(1) space since the toLowerCase() and toUpperCase() calls allocate new strings.


Log in to reply
 

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