题目要求

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:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
  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

        

        

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄