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".
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.
三个flag分别标注首位,末尾中间的几位的大小写状态。比较flag判定是否满足要求。
public boolean detectCapitalUse(String word) {
char[] array = word.toCharArray();
if (array.length == 1)
return true;
int flag1 = 0;
int flag2 = 0;
int flag3 = 0;
if (array[array.length - 1] >= 'A' && array[array.length - 1] <= 'Z')
flag3 = 1;
else if (array[array.length - 1] >= 'a' && array[array.length - 1] <= 'z')
flag3 = 0;
if (array[0] >= 'A' && array[0] <= 'Z')
flag1 = 1;
else if (array[0] >= 'a' && array[0] <= 'z')
flag1 = 0;
for (int i = array.length - 1; i >= 1; i--) {
System.out.println(array[i]);
if (array[i] >= 'A' && array[i] <= 'Z')
flag2 = 1;
else if (array[i] >= 'a' && array[i] <= 'z')
flag2 = 0;
if (flag2 != flag3)
return false;
}
if (flag1 == 0 && flag2 == 1)
return false;
return true;
}