LeetCode 520 Detect Capital 解题报告

题目要求

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 are not capitals, like "leetcode".
  3. 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.

题目分析及思路

要求判断一个给定词对字母大写的使用是否正确。正确使用需满足三个条件中的任意一个:1)全部大写;2)全部小写;3)当不只一个字母时,首字母大写,其余字母小写。可以先得到给定词中大写字母的个数,若和给定词长度相等,或者为0,又或者为1且该词首字母大写,则返回true,否则返回false。

python代码

class Solution:

    def detectCapitalUse(self, word: str) -> bool:

        count = 0

        for c in word:

            if c.isupper():

                count += 1

        if count == len(word) or count == 0 or (count==1 and word[0].isupper()):

            return True

        else:

            return False

        

        

 

posted on 2019-04-09 14:44  锋上磬音  阅读(105)  评论(0编辑  收藏  举报