Skip to content

Latest commit

 

History

History
101 lines (78 loc) · 2.25 KB

File metadata and controls

101 lines (78 loc) · 2.25 KB

English Version

题目描述

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

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

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

 

示例 1:

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

示例 2:

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

 

提示:

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

解法

方法一

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        cnt = 0
        for c in word:
            if c.isupper():
                cnt += 1
        return cnt == 0 or cnt == len(word) or (cnt == 1 and word[0].isupper())
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)));
    }
}
class Solution {
public:
    bool detectCapitalUse(string word) {
        int cnt = 0;
        for (char c : word)
            if (isupper(c)) ++cnt;
        return cnt == 0 || cnt == word.size() || (cnt == 1 && isupper(word[0]));
    }
};
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])))
}