列表

详情


520. 检测大写字母

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

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

 

示例 1:

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

示例 2:

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

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: bool detectCapitalUse(string word) { } };

python3 解法, 执行用时: 35 ms, 内存消耗: 16.4 MB, 提交时间: 2024-06-23 10:57:16

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        return word.islower() or word.isupper() or word.istitle()


    def detectCapitalUse2(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()

java 解法, 执行用时: 1 ms, 内存消耗: 41.1 MB, 提交时间: 2024-06-23 10:56:46

public 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));
    }
}

rust 解法, 执行用时: 0 ms, 内存消耗: 2.1 MB, 提交时间: 2024-06-23 10:56:24

impl Solution {
    pub fn detect_capital_use(word: String) -> bool {
        let cnt = word.chars().filter(|&c| c.is_uppercase()).count();
        cnt == 0 || cnt == word.len() || cnt == 1 && word.chars().next().unwrap().is_uppercase()
    }
}

javascript 解法, 执行用时: 65 ms, 内存消耗: 49.8 MB, 提交时间: 2024-06-23 10:56:09

/**
 * @param {string} word
 * @return {boolean}
 */
var detectCapitalUse = function(word) {
    const cnt = _.sumBy(word, c => c === c.toUpperCase() ? 1 : 0);
    return cnt === 0 || cnt === word.length || cnt === 1 && word[0] === word[0].toUpperCase();
};

cpp 解法, 执行用时: 0 ms, 内存消耗: 7.4 MB, 提交时间: 2024-06-23 10:55:41

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

golang 解法, 执行用时: 0 ms, 内存消耗: 2 MB, 提交时间: 2021-06-23 18:32:17

func detectCapitalUse(word string) bool {
    if unicode.IsUpper(rune(word[0])) {
        return strings.ToUpper(word[1:]) == word[1:] || strings.ToLower(word[1:]) == word[1:]
    }
    return strings.ToLower(word) == word
}

上一题