Simple Solution


  • 0
    P

    Analysis
    As mentioned in the question, we have 3 cases to decide if the usage of capitals in a word is right or wrong. By converting each of these cases into a condition we can devise solution for this problem

    Case 1

    • All letters in this word are capitals, like "USA".
      -- To determine if all letters in this word are capitals, we can make use of existing String
      methods in Java , i.e toUpperCase() and equals() in the following way
      word.equals(word.toUpperCase())
      

    Case 2

    • All letters in this word are not capitals, like "leetcode".
      --Similarly, as above , we now can use equals() and toLoweCase() methods of String class
    word.equals(word.toLowerCase())
    

    Case 3

    • Only the first letter in this word is capital if it has more than one letter, like "Google".
      --In this case, we will check if the first character is a capital using isUpperCase method of Character class and also check if the remaining letters in the words are lowerCase in the following way.
      (Character.isUpperCase(word.charAt(0)) word.substring(1).equals(word.substring(1).toLowerCase()))

    Code -

    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()) );
        }
    

Log in to reply
 

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