LeetCode练习.Java题目
题目要求:
* 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.题目的要求是,输入一个字符串,判断字符串中大写字母的位置 , 以下三种情况可以返回true , 其余的返回false:
1 全部是大写字母
2 全部是小写字母
3 只有第一个字母是大写字母
/**
* 我的思路是定义如下两个变量 , count和seq . 然后将字符串转换成StringBuilder , 这样就可以一个一个字母的访问了 * count用于统计大写字母的个数 , seq用于记录大写字母的位置
* isUpperCase 用于判断字母是否为大写字母,是就为true , 不是就为 false
* count==0对应于第3种情况
* count==word.length 对应与第一种情况
* count == 1 , 且seq == 0(大写字母位于第0个位置)则对应于第2种情况
* @param word
* @return
*/
public static boolean detectCapitalUse(String word){
int count= 0; //统计大写字母的个数
int seq = 0;
StringBuilder strBuild = new StringBuilder(word);
for (int i = 0; i < strBuild.length(); i++) {
if(Character.isUpperCase(strBuild.charAt(i))){
count++;
seq = i;
}
}
System.out.println(strBuild.length() + "\t" + count + "\t" + seq);
if(strBuild.length() == count || count == 0 ||(count == 1 && seq ==0)) {
return true;
}
else{
return false;
}
}
参考LeetCode上大神的写法:
/**
* 利用正则化的方法
* 全是大写字母[A-Z]+
* 全是小写字母[a-z]+
* 第一个大写后面的都小写[A-Z][a-z]+
* @param word
* @return
*/
public static boolean detectCapitalUse1(String word) {
return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+");
}
正则化确实厉害 , 这种思路更加厉害 .