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.
Subscribe to see which companies asked this question.
通过代码如下:
public class Solution {
public boolean detectCapitalUse(String word) {boolean flag=false;
int small=0;
int big=0;
char[] temp=word.toCharArray();
System.out.println("word:"+word);
if(word.length()==1){
if(temp[0]>='A' && temp[0]<='Z')
{
return true;
}
}
for(int i=0;i<temp.length;i++){
if(temp[i]>='A' && temp[i]<='Z')
{
big=big+1;
}
else if(temp[i] >= 'a' && temp[i]<='z')
{
small=small+1;
}
}
//第一种,判断是否全为大写
if(big==temp.length){
flag=true;
return flag;
}
//第二种,判断是否全为小写
else if(small==temp.length){
flag=true;
return flag;
}
else if(temp[word.length()-1]>='A' && temp[word.length()-1]<='Z'&&big==1 && small==(temp.length-1)){
flag=false;
return flag;
}
else if(big==1 && small==(temp.length-1) && temp[0]>='A' && temp[0]<='Z')
{
flag=true;
}
System.out.println("big:"+big+",small:"+small);
return flag;
}
}