1193. 检测大写的正确性

描述

给定一个单词,你需要判断其中大写字母的使用是否正确。

当下列情况之一成立时,我们将单词中大写字母的用法定义为正确:

这个单词中的所有字母都是大写字母,如“USA”。
这个单词中的所有字母都不是大写字母,如“leetcode”。
如果它有多个字母,例如“Google”,那么这个单词中的第一个字母就是大写字母。
否则,我们定义该单词没有以正确的方式使用大写字母。

输入将是一个由大写和小写拉丁字母组成的非空单词。

样例

输入: "USA"
输出: True

输入: "FlaG"
输出: False
这题可以分为两个逻辑

如果从第一个字母开始,全是大写,那么是对的
如果从第二个字母开始,全是小写,那么也是对的。
public class Solution {
    /**
     * @param word: a string
     * @return: return a boolean
     */
    public boolean detectCapitalUse(String word) {
        // write your code here
        if(word == null || word.length() == 0){
            return false;
        }
        if(word.length() == 1){
            return true;
        }
        
        boolean firstCap = Character.isUpperCase(word.charAt(0));
        boolean secondCap = Character.isUpperCase(word.charAt(1));
        if(firstCap == false){
            for(int i = 1; i < word.length(); i++){
                if(Character.isUpperCase(word.charAt(i))){
                    return false;
                }
            }
            return true;
        }
        if(word.length() == 2){
            return true;
        }
        
        if(secondCap == true){
            for(int i = 2; i < word.length(); i++){
                if(!Character.isUpperCase(word.charAt(i))){
                    return false;
                }
            }
            return true;
        }
        else{
            for(int i = 2; i < word.length(); i++){
                if(Character.isUpperCase(word.charAt(i))){
                    return false;
                }
            }
            return true;
        }
    }
}
Description
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".
Otherwise, we define that this word doesn't use capitals in a right way.

The input will be a non-empty word consisting of uppercase and lowercase latin letters.
posted @ 2019-04-02 21:48  故人叹  阅读(253)  评论(0)    收藏  举报