直接根据base case进行循环遍历求所不满足的条件,很简单的一道题。
class Solution {
public boolean detectCapitalUse(String word) {
//base case three status
//one all word is large
//two all word is small
//three different the first must be the large other is small
boolean firstLarge = false;
boolean small = false;
boolean large = false;
for(int i =0 ; i < word.length();i++){
if(i == 0){
if(word.charAt(i) >= 'A' && word.charAt(i) <= 'Z'){
//大写开头
firstLarge = true;
}else if (word.charAt(i) >= 'a' && word.charAt(i) <= 'z'){
//全部小写
small = true;
}
}else{
if(word.charAt(i) >= 'A' && word.charAt(i) <= 'Z'){
//大写开头
large = true;
}else if (word.charAt(i) >= 'a' && word.charAt(i) <= 'z'){
//全部小写
small = true;
}
if((firstLarge && large && small) || (large && small)){
return false;
}
}
}
return true;
}
}
看评论,根据大小写的数量也是很好的思路。
时间复杂度:O(n)
空间复杂度:O(3) --(效率会更快,最差情况下为O(n))
空间换时间