520. Detect Capital(檢測數組的大小寫)

Given a word, you need to judge whether the usage of capitals in it is right or not.api

We define the usage of capitals in a word to be right when one of the following cases holds:this

  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.spa

 

Example 1:code

Input: "USA"
Output: True

 

Example 2:blog

Input: "FlaG"
Output: False

思路:將單詞轉換爲大寫獲得up,將單詞轉換爲小寫獲得low,若word與up或與low相等,則返回true,
不然去掉word的首字母獲得last,若last轉換爲小寫後仍與last相等,則返回true,
不然返回false。
public boolean detectCapitalUse(String word) {
        int len=word.length();
        String up = word.toUpperCase();  
        String low = word.toLowerCase();  
        if (word.equals(up) || word.equals(low))  
            return true;  
         String last = word.substring(1, len);  
        if (last.toLowerCase().equals(last))  
           return true;  
         return false;  
    }
相關文章
相關標籤/搜索