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:
- 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.
基本思路:
由题可知,字符的长度>=1。
当字符串长度等于1时,任何字符串都符合要求;
当字符串长度大于1时,符合要求的字符串有三种,全是大写字母、全是小写字母、首字符为大写其余字符为小写字母。
class Solution {
public boolean detectCapitalUse(String word) {
int firstLetter = -1;
if(word.length()<2)return true;
if(Character.isLowerCase(word.charAt(0))&&!Character.isLowerCase(word.charAt(1)))
return false;
if(!Character.isLowerCase(word.charAt(0))&&!Character.isLowerCase(word.charAt(1)))
firstLetter = 0;
if(Character.isLowerCase(word.charAt(0))&&Character.isLowerCase(word.charAt(1)))
firstLetter = 1;
if(!Character.isLowerCase(word.charAt(0))&&Character.isLowerCase(word.charAt(1)))
firstLetter = 2;
if(firstLetter == 0){
for(int i=2;i<word.length();i++){
if(Character.isLowerCase(word.charAt(i))==true)
return false;
}
} else{
for(int i=2;i<word.length();i++){
if(Character.isLowerCase(word.charAt(i))==false)
return false;
}
}
return true;
}
}
进阶思路:
符合要求的字符串有三种情况:全大写、全小写、第一个大写其余小写。
全大写意味着字符串中大写字符的个数=word.length();
全小写意味着字符串中大写字符的个数=0;
第一个大写意味着字符串中大写字符的个数=1且字符串的首字符是大写。
class Solution {
public boolean detectCapitalUse(String word) {
int count = 0;
for(int i=0;i<word.length();i++){
if(Character.isUpperCase(word.charAt(i)))count++;
}
if(word.length() == count ||0 == count||(1 == count && Character.isUpperCase(word.charAt(0))))
return true;
return false;
}
}
终极思路:
/*
全大写 [A-Z]+
全小写 [a-z]+
第一个大写其余小写 [A-Z][a-z]+
*/
class Solution {
public boolean detectCapitalUse(String word) {
return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+");
}
}