LeetCode每日一题: 检测大写字母(No.520)

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

内容简介:}
给定一个单词,你需要判断单词的大写使用是否正确。
我们定义,在以下情况时,单词的大写用法是正确的:
1、全部字母都是大写,比如"USA"
2、单词中所有字母都不是大写,比如"leetcode"
3、如果单词不只含有一个字母,只有首字母大写, 比如 "Google"
否则,我们定义这个单词没有正确使用大写字母。
复制代码

示例:

输入: "USA"
输出: True

输入: "FlaG"
输出: False
复制代码

思考:

这题分三种情况:全大写、全小写、只有首字母大写。其他情况皆是false
所以用一个value记录大写字符个数,循环字符串字符,是大写字母value+1
最后根据value的值判断结果,如果相等则说明字符全大写返回true。如果value0说明全小写返回true
如果value等于1,在查看首字符是否为大写,是则返回true,否则返回false
复制代码

实现:

class Solution {
public boolean detectCapitalUse(String word) {
    char[] letters = word.toCharArray();
    int len = letters.length;
    int value = 0;
    for(int i = 0;i < len;i++){
        if(letters[i] <= 'Z' && letters[i] >= 'A'){
            value = value + 1;
        }
    }
    if(value == len || value == 0)
        return true;
    if(value == 1 && letters[0] <= 'Z' && letters[0] >= 'A')
        return true;
    return false;
}
复制代码

}


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

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

We Are the Nerds

We Are the Nerds

Christine Lagorio-Chafkin / Hachette Books / 2018-10-2 / USD 18.30

Reddit hails itself as "the front page of the Internet." It's the third most-visited website in the United States--and yet, millions of Americans have no idea what it is. We Are the Nerds is an eng......一起来看看 《We Are the Nerds》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

SHA 加密
SHA 加密

SHA 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器