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

        

        

 

转载于:https://www.cnblogs.com/yao1996/p/10676768.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值