Similar Problems

Similar Problems not available

Detect Capital - Leetcode Solution

Companies:

LeetCode:  Detect Capital Leetcode Solution

Difficulty: Easy

Topics: string  

Problem Statement:

Given a word, you need to judge whether the usage of capitals in it is right or not.

We define the usage of capitals in a word to be right when one of the following cases holds:

  1. All letters in this word are capitals, like "USA".
  2. All letters in this word except for the first one are capitals, like "leetcode".
  3. All letters in this word are not capitals, like "Google".

Otherwise, we define that this word doesn't use capitals in a right way.

Example 1:

Input: "USA" Output: True

Example 2:

Input: "FlaG" Output: False

Solution:

Let's go through the solution step-by-step:

  • Check if all letters are in uppercase using the isupper() method.

  • If yes, the word follows the first case, so return True.

  • Check if all letters are in lowercase using the islower() method.

  • If yes, the word follows the third case, so return True.

  • Check if the first letter of the word is uppercase and the rest of the letters are lowercase using the istitle() method.

  • If yes, the word follows the second case, so return True.

  • If none of the above cases is true, return False.

Implementation:

def detectCapitalUse(word: str) -> bool:
if word.isupper() or word.islower():
return True
elif word.istitle():
return True
else:
return False

Time Complexity:

O(n), where n is the length of the input word.

Space Complexity:

O(1), as we are not using any extra space.

Detect Capital Solution Code

1