1. 程式人生 > >LeetCode-520. Detect Capital

LeetCode-520. Detect Capital

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:

  1. All letters in this word are capitals, like "USA".
  2. All letters in this word are not capitals, like "leetcode".
  3. 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.

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]+");
    }
}