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

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



你可能感兴趣的:(Java,算法,面试,LeetCode,520.,Detect,Capital,检测,单词,大写字母)