leetcode 520. 檢測大寫字母

給定一個單詞,你需要判斷單詞的大寫使用是否正確。

我們定義,在以下情況時,單詞的大寫用法是正確的:

全部字母都是大寫,比如"USA"。
單詞中所有字母都不是大寫,比如"leetcode"。
如果單詞不只含有一個字母,只有首字母大寫, 比如 "Google"。
否則,我們定義這個單詞沒有正確使用大寫字母。

示例 1:

輸入: "USA"
輸出: True
示例 2:

輸入: "FlaG"
輸出: False
注意: 輸入是由大寫和小寫拉丁字母組成的非空單詞。

方法:根據大寫字母個數判斷

class Solution {
    public boolean detectCapitalUse(String word) {
        int len = word.length();
        int count = 0;
        int index = -1;
        for(int i = 0; i < len; i++){
            if(word.charAt(i) <= 'Z' && word.charAt(i) >= 'A'){
                index = i;
                count++;
            }
        }
        if(count == 0 || count == len)
            return true;
        if(count == 1 && index == 0)
            return true;
        return false;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章