leetcode-520-Detect-Capital

描述


Given a word, you need to judge whether the usage of capitals in it is right or not.

We define the usage of capitals in a word to be right when one of the following cases holds:

  1. All letters in this word are capitals, like “USA”.
  2. All letters in this word are not capitals, like “leetcode”.
  3. Only the first letter in this word is capital if it has more than one letter, like “Google”.

Otherwise, we define that this word doesn’t use capitals in a right way.

Example 1:

1
2
Input: "USA"
Output: True

Example 2:

1
2
Input: "FlaG"
Output: False

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

分析


题意是要判断一个单词的大小写是否正确,方法很多。

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
class Solution {
public boolean detectCapitalUse(String word) {
int upperCount = 0;
for (int i = 0; i < word.length(); i++) {
if ('A' <= word.charAt(i) && word.charAt(i) <= 'Z') {
upperCount++;
}
}
return upperCount == 0 || upperCount == word.length() || 'A' <= word.charAt(0) && word.charAt(0) <= 'Z' && upperCount == 1;
}
}

先统计单词中大写字母的个数,如果大写字母数量为0(该单词全是小写字母),或者大写字母个数为单词的长度(该单词全是大写字母),或者单词的第一个字母是大小,大写字母的个数为1(该单词只有第一个字母是大写的),则这个单词的大小写没有问题。

解决方案2(Java)


1
2
3
4
5
class Solution {
public boolean detectCapitalUse(String word) {
return word.equals(word.toUpperCase()) || word.substring(1).equals(word.substring(1).toLowerCase());
}
}

评论区里有一个一行代码的解决方案还挺有意思的,直接判断转换成小写后的结果。

题目来源