题目原址
https://leetcode.com/problems/detect-capital/description/
题目描述
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.
Eample1:
Input: “USA”
Output: True
Example2:
Input: “FlaG”
Output: False
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
解题思路
题目描述中显示:
以下三种情况都满足题意
1. 单词的第一个字母是小写的,剩余的字母都是小写的
2. 单词的第二个字母是大写的,剩余的字母都是小写的
3. 单词的第二个字母是大写的,剩余的字母都是大写的
根据题目描述可以看出,
(1)先判断单词是否为空,当单词为空或者只有一个字母时,该单词满足题意
(2)判断单词的第一个字母是否是大写的,如果是大写的,判断单词是否超过2个字母,如果是,通过for循环判断剩余的单词是否全是大写的或者全是小写的,如果是,该单词满足题意
(3)判断单词的第一个字母是否是小写的,如果是小写的,通过for循环判断剩余的字母是否是小写的,如果都是小写的,该单词满足题意
AC代码
class Solution {
public boolean detectCapitalUse(String word) {
boolean ret = false;
char w[] = word.toCharArray();
if(w.length == 0 || w.length == 1)
return true;
if(w[0] >= 65 && w[0] <= 90) { //第一个元素是大写
if(w.length > 2) {
if(w[1] >= 65 && w[1] <= 90){ // 第二个元素是大写
for(int i = 1; i < w.length; i++){
if(w[i] <65 || w[i] > 90)
return false;
}
return true;
}else if(w[1] >= 97 && w[1] <= 122){
for(int i = 1; i < w.length; i++){
if(w[i] <97 || w[i] > 122)
return false;
}
return true;
}
}
}else if(w[0] >= 97 && w[0] <= 122) { //小写
for(int i = 1; i < w.length; i++) {
if(w[i] <97 || w[i] > 122)
return false;
}
}
return true;
}
}