Leetcode——520. Detect Capital

题目原址

https://leetcode.com/problems/detect-capital/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:

  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.

Eample1:

Input: “USA”
Output: True

Example2:

Input: “FlaG”
Output: False

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

解题思路

题目描述中显示:
以下三种情况都满足题意
1. 单词的第一个字母是小写的,剩余的字母都是小写的
2. 单词的第二个字母是大写的,剩余的字母都是小写的
3. 单词的第二个字母是大写的,剩余的字母都是大写的

根据题目描述可以看出,
(1)先判断单词是否为空,当单词为空或者只有一个字母时,该单词满足题意
(2)判断单词的第一个字母是否是大写的,如果是大写的,判断单词是否超过2个字母,如果是,通过for循环判断剩余的单词是否全是大写的或者全是小写的,如果是,该单词满足题意
(3)判断单词的第一个字母是否是小写的,如果是小写的,通过for循环判断剩余的字母是否是小写的,如果都是小写的,该单词满足题意

AC代码

class Solution {
    public boolean detectCapitalUse(String word) {
        boolean ret = false;
        char w[] = word.toCharArray();
        if(w.length == 0 || w.length == 1)
            return true;
        if(w[0] >= 65 && w[0] <= 90) {  //第一个元素是大写
            if(w.length > 2) {
                if(w[1] >= 65 && w[1] <= 90){ // 第二个元素是大写
                    for(int i = 1; i < w.length; i++){
                        if(w[i] <65 || w[i] > 90)
                            return false;
                    }
                    return true;
                }else if(w[1] >= 97 && w[1] <= 122){
                    for(int i = 1; i < w.length; i++){
                        if(w[i] <97 || w[i] > 122)
                            return false;
                    }
                    return true;
                }
            }
        }else if(w[0] >= 97 && w[0] <= 122) { //小写
            for(int i = 1; i < w.length; i++) {
                if(w[i] <97 || w[i] > 122)
                    return false;
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值