我们定义,在以下情况时,单词的大写用法是正确的:
- 全部字母都是大写,比如
"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])))
}