Fast & Clean Java Solution (defeat 80%)

  • 0

    The idea is to count the number of uppercase letters

    public boolean detectCapitalUse(String word) {
            if(word.length() == 1) return true;
            //the following cases should contain at least two characters
            Character c1 = word.charAt(0);
            Character c2 = word.charAt(1);
            int u = 0;
            for (Character c : word.toCharArray()){
                if(Character.isUpperCase(c)) u++;
            if (Character.isUpperCase(c1)){
                if (u == word.length()) return true;//all capital
                if (u == 1) return true;//only the first character is capitalized
                else return false;
            } else {
                if (u == 0) return true;//all in lowercase
                else return false;

Log in to reply

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