描述
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:
- All letters in this word are capitals, like “USA”.
- All letters in this word are not capitals, like “leetcode”.
- 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 | Input: "USA" |
Example 2:
1 | Input: "FlaG" |
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
分析
题意是要判断一个单词的大小写是否正确,方法很多。
解决方案1(Java)
1 | class Solution { |
先统计单词中大写字母的个数,如果大写字母数量为0(该单词全是小写字母),或者大写字母个数为单词的长度(该单词全是大写字母),或者单词的第一个字母是大小,大写字母的个数为1(该单词只有第一个字母是大写的),则这个单词的大小写没有问题。
解决方案2(Java)
1 | class Solution { |
评论区里有一个一行代码的解决方案还挺有意思的,直接判断转换成小写后的结果。