Skip to content

[520] Detect Capital

https://leetcode.com/problems/detect-capital/description/

  • algorithms
  • Easy (51.95%)
  • Source Code: 520.detect-capital.py
  • Total Accepted: 82K
  • Total Submissions: 156.5K
  • Testcase Example: '"USA"'

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:

All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in this word is capital if it has more than one letter, 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

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

python
class Solution(object):
    def detectCapitalUse(self, word):
        """
        :type word: str
        :rtype: bool
        """
        lenw = len(word)

        if lenw == 1: return True

        if 'a' <= word[0] <= 'z':
            for i in range(1, lenw):
                if not 'a'<=word[i]<='z': return False

        if 'A' <= word[0] <= 'Z':
            if 'A' <= word[1] <= 'Z':
                for i in range(2, lenw):
                    if not 'A' <= word[i] <= 'Z': return False

            if 'a' <= word[1] <= 'z':
                for i in range(2, lenw):
                    if not 'a' <= word[i] <= 'z': return False

        return True

Last updated: