520. Detect Capital

我的code,就是阅读理解,但是比较完备,tolerant String可能不规范的情况。

    public boolean detectCapitalUse(String word) {
        if (word == null || word.length() <= 1) {
            return true;
        }
        for (int i = 0; i < word.length(); i++) {
            //首字母小写
            if (isLowerCaseLetter(word.charAt(0))) {
                if (!isLowerCaseLetter(word.charAt(i))) {
                    return false;
                }
            }
            //首字母大写
            else if (isUpperCaseLetter(word.charAt(0))) {
                if (isUpperCaseLetter(word.charAt(1))) {
                    if (i > 1 && !isUpperCaseLetter(word.charAt(i))) {
                        return false;
                    }
                } else if (isLowerCaseLetter(word.charAt(1))) {
                    if (i > 1 && !isLowerCaseLetter(word.charAt(i))) {
                        return false;
                    }
                }
            } else {
                return false;
            }
        }
        return true;
    }

    private boolean isLowerCaseLetter(char c) {
        return c <= 'z' && c >= 'a';
    }

    private boolean isUpperCaseLetter(char c) {
        return c <= 'Z' && c >= 'A';
    }

简洁的代码:

public class Solution {
    public boolean detectCapitalUse(String word) {
        int cnt = 0;
        for(char c: word.toCharArray()) if('Z' - c >= 0) cnt++;
        return ((cnt==0 || cnt==word.length()) || (cnt==1 && 'Z' - word.charAt(0)>=0));
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,630评论 25 709
  • 写了这么多题,感觉用go写真方便,可以直接对解题的函数进行测试,测试代码写起来也好方便,多个测试用例很方便就放在一...
    miltonsun阅读 464评论 0 0
  • 题目 Given a word, you need to judge whether the usage of c...
    Eazow阅读 353评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,269评论 19 139
  • 老五回来了,带着老婆孩子。 老五在城南旧街找了一间房子,把老婆孩子先安顿好。随后,他去了旧街的旧货市场买了一张雕花...
    茶人老七阅读 314评论 2 1