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.

 

一開始沒多想,就只是單純使用 ascii 來判斷大小寫,前面判斷長度,則是為了避免 ArrayOutOfBound 錯誤

class Solution {
    public boolean detectCapitalUse(String word) {
        char[] wordElements = word.toCharArray();
        int wordLength = word.length();
        
        if(wordLength == 1) {
            return true;
        }
        
        if(isLower(wordElements[0])) {
            for(int i=1; i<wordLength; i++) {
                if(isUpper(wordElements[i])) return false;
            }
        } else if (isUpper(wordElements[0]) && isUpper(wordElements[1])) {
            for(int i=2; i<wordLength; i++) {
                if(isLower(wordElements[i])) return false;
            }
        } else if (isUpper(wordElements[0]) && isLower(wordElements[1])) {
            for(int i=2; i<wordLength; i++) {
                if(isUpper(wordElements[i])) return false;
            }
        }
        
        return true;
    }
    
    private boolean isUpper(char element) {
        return element >=  65 && element <= 90;
    }
    
    private boolean isLower(char element) {
        return element >= 97 && element <= 122;
    }
}

後來研究了其他人解法發現可以直接使用 String 所提供的 toUpperCase 和 toLowerCase 直接比較是否全大寫或全小寫

而字首大寫其他部分小寫,則可以用 Character 的 isUpperCase 搭配即可

public boolean detectCapitalUse(String word) {
    return word.equals(word.toUpperCase()) || 
           word.equals(word.toLowerCase()) ||
           Character.isUpperCase(word.charAt(0)) && 
           word.substring(1).equals(word.substring(1).toLowerCase());
}

除此之外,最方便的應該還是使用正規表示式

? 代表出現 0 或 1 次

* 則是出現 0 或 1 次以上

public boolean detectCapitalUse(String word) {
    return word.matches("[A-Z]*|[A-Z]?[a-z]*");
}


 

參考網址

https://www.javaworld.com.tw/jute/post/view?bid=20&id=130126

https://leetcode.com/problems/detect-capital/discuss/99298/Java-1-Liner

https://leetcode.com/problems/detect-capital/discuss/99274/Simple-Java-Solution-O(n)-time-O(1)-space