LeetCode520. Detect Capital--檢測單詞的大寫字母是否符合規範
阿新 • • 發佈:2019-02-18
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".//只有首字母大寫,其餘小寫。單詞只有一個字元時大小寫都行
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.
package com.main; public class Main { //AC的第一種方法,檢測每個字元 public boolean detectCapitalUse2(String word) { if (word.length() == 1) return true; if (Character.isUpperCase(word.charAt(0))) {//首字母大寫 if (Character.isUpperCase(word.charAt(1))) {//第二個字元大寫 for (int i = 2; i < word.length(); i++) { if (!Character.isUpperCase(word.charAt(i))) { return false; } } return true; } else if (!Character.isUpperCase(word.charAt(1))) {//第二個字元小寫 for (int i = 2; i < word.length(); i++) { if (Character.isUpperCase(word.charAt(i))) { return false; } } return true; } else return false; } else {//首字母小寫 for (int i = 1; i < word.length(); i++) { if (Character.isUpperCase(word.charAt(i))) { return false; } } return true; } }//detectCapitalUse //AC的第二種方法,直接計數 public boolean detectCapitalUse(String word) { int count = 0; for (char c : word.toCharArray()) { if ('Z' - c >= 0) count++; } return (count == 0 || count == word.length() || (count == 1 && 'Z' - word.charAt(0) >= 0)); } public static void main(String[] args) { System.out.println(new Main().detectCapitalUse2("ffffffffffffffffffffF")); }//main } //false