[Leetcode] 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.

思路

练手题目。不过不知道为啥,我在VS下面用isupper函数来判断word[i]是不是大写字母,可以通过对“USA”这个例子的测试;然而在Leetcode测试平台上,却只能用来(word[i] >= 'A' && word[i] <= 'Z')测试才行。这是不是Leetcode测试平台上的一个小bug?知道原因的读者请留言。。。

代码

class Solution {
public:
    bool detectCapitalUse(string word) {
        if (word.length() == 1) {
            return true;
        }
        else {
            bool first_upper = word[0] >= 'A' && word[0] <= 'Z';
            bool second_upper = word[1] >= 'A' && word[1] <= 'Z';
            bool right_case = first_upper ? second_upper : false;
            for (int i = 1; i < word.length(); ++i) {
                if ((word[i] >= 'A' && word[i] <= 'Z') != right_case) {
                    return false;
                }
            }
            return true;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值