​LeetCode刷题实战520: 检测大写字母

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 检测大写字母,我们先来看题面:
https://leetcode-cn.com/problems/detect-capital/

We define the usage of capitals in a word to be right when one of the following cases holds:


All letters in this word are capitals, like “USA”.

All letters in this word are not capitals, like “leetcode”.

Only the first letter in this word is capital, like “Google”.


Given a string word, return true if the usage of capitals in it is right.


我们定义,在以下情况时,单词的大写用法是正确的:
  • 全部字母都是大写,比如 “USA” 。

  • 单词中所有字母都不是大写,比如 “leetcode” 。

  • 如果单词不只含有一个字母,只有首字母大写, 比如 “Google” 。

给你一个字符串 word 。如果大写用法正确,返回 true ;否则,返回 false 。

示例                         

示例 1
输入:word = "USA"
输出:true

示例 2
输入:word = "FlaG"
输出:false


解题

可以通过比较大写字母的个数与当前下标的大小来判断字符串是否连续大写,如果大写字母个数小于当前下标则返回false,最后再判断是否都是大写字母或者只有首字母大写。

class Solution {
public:
    bool detectCapitalUse(string word) {
        int upCt=0;
        for(int i=0;i<word.length();i++) {
            if(isupper(word[i])) {
                if(upCt<i) {
                    return false;
                }
                upCt++;
            }
        }
        return upCt==word.length() || upCt<=1;
    }
};


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-500题汇总,希望对你有点帮助!
LeetCode刷题实战501:二叉搜索树中的众数
LeetCode刷题实战502:IPO
LeetCode刷题实战503:下一个更大元素 II
LeetCode刷题实战504:七进制数
LeetCode刷题实战505:迷宫II
LeetCode刷题实战506:相对名次
LeetCode刷题实战507:完美数
LeetCode刷题实战508:出现次数最多的子树元素和
LeetCode刷题实战509:斐波那契数
LeetCode刷题实战510:二叉搜索树中的中序后继 II
LeetCode刷题实战511:游戏玩法分析 I
LeetCode刷题实战512:游戏玩法分析 II
LeetCode刷题实战513:找树左下角的值
LeetCode刷题实战514:自由之路
LeetCode刷题实战515:在每个树行中找最大值
LeetCode刷题实战516:最长回文子序列
LeetCode刷题实战517:超级洗衣机
LeetCode刷题实战518:零钱兑换 II

​LeetCode刷题实战520: 检测大写字母

本篇文章来源于微信公众号:程序IT圈

原创文章,作者:栈长,如若转载,请注明出处:https://www.cxyquan.com/19301.html

(0)
上一篇 2022年2月6日 13:52
下一篇 2022年2月8日 13:52

相关推荐

发表评论

登录后才能评论