Very short and simple solution(C# example)


  • 0
    A

    In the description of our task we have three cases for checking .

    • Check if all letters are Uppercase letters
       word.ToUpper();
    
    • Check if all letters are Lowercase letters
       word.ToLower();
    
    • Check if first letter is uppercase and others are lowercase

      If first letters are uppercase :

       word[0] == Char.ToUpper(word[0]) 
    

    And if all leters without first are lowercase :

      word.Substring(1) == word.Substring(1).ToLower()
    

    After putting together all these cases we have a complete solution :

     public bool DetectCapitalUse(string word)
     {
          return word == word.ToLower()
           || word == word.ToUpper()
           || (word[0] == Char.ToUpper(word[0])
                      && word.Substring(1) == word.Substring(1).ToLower());
     }
    

    Also a good way to solve this task is to use Regex .


Log in to reply
 

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