LeetCode 520 Detect Capital

栏目: 编程工具 · 发布时间: 7年前

内容简介:给与一个单词,判断其大写字母的使用是否正确,即每个字母都是大写或都是小写,或首字母大写。Example 1:Example 2:

给与一个单词,判断其大写字母的使用是否正确,即每个字母都是大写或都是小写,或首字母大写。

Example 1:

Input: "USA"
Output: True

Example 2:

Input: "FlaG"
Output: False

解法

定义两个变量,记录小写字母个数和大写字母个数,然后判断条件是否符合。

class Solution {
    public boolean detectCapitalUse(String word) {
        if (word.length() < 2) {
            return true;
        }
        char[] chars = word.toCharArray();
        int lower = 0, upper = 0;
        for (int i = 0; i < chars.length; i++) {
            if (isLowerCaseLetter(chars[i])) {
                lower++;
            } else {
                upper++;
            }
        }
        
        return lower == chars.length || upper == chars.length ||
                (isUpperCaseLetter(chars[0]) && lower == chars.length - 1);
    }
    
    public boolean isUpperCaseLetter(char c) {
        return c >= 65 && c <= 90;
    }
    
    public boolean isLowerCaseLetter(char c) {
        return c >= 97 && c <= 122;
    }
}
Runtime: 12 ms, faster than 98.36% of Java online submissions for Detect Capital.

以上所述就是小编给大家介绍的《LeetCode 520 Detect Capital》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Programming Concurrency on the JVM

Programming Concurrency on the JVM

Venkat Subramaniam / The Pragmatic Bookshelf / 2011-6-1 / USD 35.00

Concurrency on the Java platform has evolved, from the synchronization model of JDK to software transactional memory (STM) and actor-based concurrency. This book is the first to show you all these con......一起来看看 《Programming Concurrency on the JVM》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具