LeetCode-520. Detect Capital

本文介绍了一种判断单词大小写格式是否正确的算法实现,包括基础思路、进阶思路和终极思路。通过三种不同的方法来判断输入单词的大小写格式是否符合规范,即全大写、全小写或仅首字母大写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

520.Detect Capital

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:

  1. All letters in this word are capitals, like "USA".
  2. All letters in this word are not capitals, like "leetcode".
  3. 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.

基本思路:

由题可知,字符的长度>=1。

当字符串长度等于1时,任何字符串都符合要求;

当字符串长度大于1时,符合要求的字符串有三种,全是大写字母、全是小写字母、首字符为大写其余字符为小写字母。

class Solution {
    public boolean detectCapitalUse(String word) {
        int firstLetter = -1;        
        if(word.length()<2)return true;
        if(Character.isLowerCase(word.charAt(0))&&!Character.isLowerCase(word.charAt(1)))
            return false;        
        if(!Character.isLowerCase(word.charAt(0))&&!Character.isLowerCase(word.charAt(1)))
            firstLetter = 0;
        if(Character.isLowerCase(word.charAt(0))&&Character.isLowerCase(word.charAt(1)))
            firstLetter = 1;
        if(!Character.isLowerCase(word.charAt(0))&&Character.isLowerCase(word.charAt(1)))
            firstLetter = 2;
        if(firstLetter == 0){
            for(int i=2;i<word.length();i++){
                if(Character.isLowerCase(word.charAt(i))==true)
                    return false;
            }
        } else{
            for(int i=2;i<word.length();i++){
                if(Character.isLowerCase(word.charAt(i))==false)
                    return false;
            }
        }
        return true;
    }
}

进阶思路:

符合要求的字符串有三种情况:全大写、全小写、第一个大写其余小写。

全大写意味着字符串中大写字符的个数=word.length();

全小写意味着字符串中大写字符的个数=0;

第一个大写意味着字符串中大写字符的个数=1且字符串的首字符是大写。

class Solution {
    public boolean detectCapitalUse(String word) {
        int count = 0;
        for(int i=0;i<word.length();i++){
            if(Character.isUpperCase(word.charAt(i)))count++;
        }
        if(word.length() == count ||0 == count||(1 == count && Character.isUpperCase(word.charAt(0))))
            return true;
        return false;
    }
}

终极思路:

/*
全大写 [A-Z]+
全小写 [a-z]+
第一个大写其余小写 [A-Z][a-z]+
*/
class Solution {
    public boolean detectCapitalUse(String word) {
        return word.matches("[A-Z]+|[a-z]+|[A-Z][a-z]+");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值