DetectCapitalOPT2 [source code]

public class DetectCapitalOPT2 {
    public boolean detectCapitalUse(String word) {
        int capCount = 0;
        int smalCount = 0;
        boolean flag = false;
        for (char c : word.toCharArray()) {
            if (c - 0 >= 65 && c-0 <=90) capCount++;
            else smalCount++;
        }
        if (smalCount == word.length() || capCount == word.length()) flag = true;
        if (smalCount == word.length() - 1 && word.charAt(0) >= 65 && word.charAt(0) <= 90) flag = true;

        return flag;
    }

    public static void main(String[] args) {
        DetectCapitalOPT2 tester = new DetectCapitalOPT2();
        String input1 = "Google";
        assert tester.detectCapitalUse(input1) == true : "fail 1";
        String input2 = "GooGle";
        assert tester.detectCapitalUse(input2) == false : "fail 2";
        String input3 = "KDJLSJ";
        assert tester.detectCapitalUse(input3) == true : "fail 3";
        String input4 = "dlkajfdl";
        assert tester.detectCapitalUse(input4) == true : "fail 4";
        String input5 = "adaDFda";
        assert tester.detectCapitalUse(input5) == false : "fail 5";
        String input6 = "G";
        assert tester.detectCapitalUse(input6) == true : "fail 6";
    }
}

这个是次优解, 26ms;

这个算法整体还是比较简洁的, 跳出了 stream 算法的框框, 想到用数学统计的思路来做, 有点类似我那个Island Perimeter的算法;

算法本身也很好理解, 这里也没有什么东西可以多讲.

不过看这个算法的时候想到一个问题, 就是如果你真的不记得对应大小写字母的 ASICII 码是什么的时候, 我记得以前想到过一个折衷的办法: 如果 c 是一个 char, 那么c >= 'A' && c <='Z'就可以判断是大写. 更深入的, 用c - 'A'这样的数值, 还可以完成更多的其他的操作;


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

Subscribe to see which companies asked this question.

Hide Tags String

results matching ""

    No results matching ""