题目:
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.
思路与步骤:
我主要想到两种思路:
1. 先判断第一个字母,如果为大写,则需要后面全为大写或者全为小写;如果是小写,则需要后面全为小写;
2. 先判断从第二个开始的所有字母,如果全为小写,则需要第一个是字母即可;如果全为大写,则需要第一个也是大写。
其他情况全返回 false。
效率还可以,但是代码看上去不够简洁,而且判断循环较多,后面学习了别人的代码,得到了一些新的思路
别人的思路:
这里只说返回 true 的情况
思路1
先计算一下word 中大写字母的数量,如果为0个大写或者全为大写,那么返回 true;如果只有一个大写,那么这个大写字母必须是第一个字母。也就这三种。然后要做的就是怎样写出漂亮的代码了。尤其要学习那些写法 ,很简洁。(代码AC了,但是有些情况没有考虑到,例如第一位是大写字母,但是后面的可能不是字母;大写字母个数为0,但是不是全为小写,而是有其他字符等)
思路2
比较原来的 word 是否与大写后的相等,如果不相等,就看其从第2个字符开始到最后的子串是否与小写后相等。主要用到几个方法 equals(); word.toUpperCase(); substring() (代码AC了,但是有些情况没有考虑到,例如第一位不是字母后面全为小写也可以通过)
思路3
正则表达式
通过学习别人的方法,发现本题有个隐藏的条件,就是默认输入的字符串只含有大小写字母,而不包含其他字符。但是在测试的时候可以用保护非字母的字符进行测试,并返回false。
编程实现:
思路1:
public class Solution {
public boolean detectCapitalUse(String s) {
if(s.length() <= 1) return true;
int i = 1;
if(Character.isLowerCase(s.charAt(0)))
while(i<s.length() && Character.isLowerCase(s.charAt(i))) i++;
else if(Character.isUpperCase(s.charAt(0)) && Character.isLowerCase(s.charAt(1)))
while(i<s.length() && Character.isLowerCase(s.charAt(i))) i++;
else if(Character.isUpperCase(s.charAt(0)))
while(i<s.length() && Character.isUpperCase(s.charAt(i))) i++;
if(i==s.length()) return true;
else return false;
}
}
思路2:
public class Solution {
public boolean detectCapitalUse(String s) {
if(s.length() == 0 || s.length() == 1) return true;
int i = 1;
for(i=1; i<s.length() && 'a'<=s.charAt(i) && s.charAt(i)<='z'; i++);
if(i==s.length() && Character.isLetter(s.charAt(0))) return true;
for(i=1; i<s.length() && 'A'<=s.charAt(i) && s.charAt(i)<='Z'; i++);
if(i==s.length() && 'A'<=s.charAt(0) && s.charAt(0)<='Z') return true;
return false;
}
}
别人的思路1:
public class Solution {
public boolean detectCapitalUse(String word) {
int numUpper = 0;
for (int i=0;i<word.length();i++) if (Character.isUpperCase(word.charAt(i))) numUpper++;
if (numUpper == 0 || numUpper == word.length()) return true;
if (numUpper == 1) return Character.isUpperCase(word.charAt(0));
return false;
//return (numUpper==0 || numUpper==word.length() || (numUpper==1 && Character.isUpperCase(word.charAt(0))));
}
}
期中最后3行可以用注释掉的那一行代替。
别人的思路2:
public class Solution {
public boolean detectCapitalUse(String word) {
return word.equals(word.toUpperCase()) || word.substring(1).equals(word.substring(1).toLowerCase()));
}
}
别人的思路3:
public class Solution {
public boolean detectCapitalUse(String word) {
return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+");
}
}