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:
Input: "USA"Output: True
Example 2:
Input: "FlaG"Output: False
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
题目含义:给定一个词,你需要判断它中的大小写使用是否正确。当以下情况之一存在时,我们将单词中大小写的使用定义为正确:这个单词中的所有字母都是大写,如“USA”。这个单词中的所有字母都不是大写,例如“leetcode”。只有此字中的第一个字母是大写,如果它有多个字母,如“Google”。否则,我们定义这个词不以正确的方式使用大写。
思路:找出所有大写字母的个数captialCount,与字符串长度做比较,都是小写字母、都是大写字母、只有首字母是大写字母的,都返回true。判断公式为:
captialCount == 0 || captialCount == word.length() || (captialCount == 1 && ('Z' - word.charAt(0) >= 0))
字母 ASCII码 十进制数
0 00110000 48
9 00111001 57
A 01000001 65
Z 01011010 90
a 01100001 97
z 01111010 122
DEL (delete) 01111111 127
1 public boolean detectCapitalUse(String word) {2 char[] words = word.toCharArray();3 int captialCount = 0;4 for (char letter : words) {5 if ('Z' - letter >= 0) captialCount++;6 } 7 return captialCount == 0 || captialCount == word.length() || (captialCount == 1 && ('Z' - word.charAt(0) >= 0)); 8 }