检测大写字母(Lc520)——统计大写字母的个数

我们定义,在以下情况时,单词的大写用法是正确的:

  • 全部字母都是大写,比如 "USA" 。
  • 单词中所有字母都不是大写,比如 "leetcode" 。
  • 如果单词不只含有一个字母,只有首字母大写, 比如 "Google" 。

给你一个字符串 word 。如果大写用法正确,返回 true ;否则,返回 false 。

示例 1:

输入:word = "USA"
输出:true

示例 2:

输入:word = "FlaG"
输出:false

提示:

  • 1 <= word.length <= 100
  • word 由小写和大写英文字母组成

问题简要描述:判断单词的大写用法是否正确

Java

class Solution {
    public boolean detectCapitalUse(String word) {
        int cnt = 0;
        for (char c : word.toCharArray()) {
            if (Character.isUpperCase(c)) {
                cnt++;
            }
        }
        return cnt == 0 || cnt == word.length() || (cnt == 1 && Character.isUpperCase(word.charAt(0)));
    }
}

 Python3

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        cnt = sum(c.isupper() for c in word)
        return cnt == 0 or cnt == len(word) or (cnt == 1 and word[0].isupper())        

TypeScript

function detectCapitalUse(word: string): boolean {
    let cnt = word.split("").reduce((pre, cur) => pre + (cur == cur.toUpperCase() ? 1 : 0), 0)
    return cnt == 0 || cnt == word.length || (cnt == 1 && word[0] == word[0].toUpperCase());    
};

C++

class Solution {
public:
    bool detectCapitalUse(string word) {
		int cnt = count_if(word.begin(), word.end(), [](char c) {return isupper(c);});
		return cnt == 0 || cnt == word.length() || (cnt == 1 && isupper(word[0]));
    }
};

Go

func detectCapitalUse(word string) bool {
	cnt := 0
	for _, c := range word {
		if unicode.IsUpper(c) {
			cnt++
		}
	}
	return cnt == 0 || cnt == len(word) || (cnt == 1 && unicode.IsUpper(rune(word[0])))
}

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值