「每日LeetCode」2021年11月13日

本文最后更新于:2023年3月19日 晚上

Lt520. 检测大写字母

520. 检测大写字母

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

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

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

示例 1:
输入:word = “USA” 输出:true
示例 2:
输入:word = “FlaG” 输出:false

提示:

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

思路

分整体分为三种情况,如果首字母为小写,接下来的都应该为小写;首字母为大写接下来的应该都为小写或者都为大写,同时有大写和小写应该返回 false;

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @param {string} word
* @return {boolean}
*/
var detectCapitalUse = function (word) {
if (!/[A-Z]/.test(word[0]))
return word.split("").every((char) => /[a-z]/.test(char));
word = word.slice(1);
let hasSmall = false,
hasCapital = false;
for (const char of word) {
if (!hasSmall && /[a-z]/.test(char)) hasSmall = true;
if (!hasCapital && /[A-Z]/.test(char)) hasCapital = true;
if (hasCapital && hasSmall) return false;
}
return true;
};