CY-Left

LeetCode基本功底

[leetcode]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.
否则,我们定义单词大小写错误。

实例 1:

Input: "USA"
Output: True

实例 2:

Input: "FlaG"
Output: False

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
注意:输入为大小写单词,且输入不为空。


解体思路

1.基础做法

这里通过 word 前两个字母确定该单词属性。

class Solution {
public:
    //97 122 65 90
    bool detectCapitalUse(string word) {
        int len = word.size();
        if(len<2) return true;
        if(len<3&&(word[0]>=97&&word[1]<=90)) return false;
        for(int i=2;i<len;i++){
            if(word[i]>=97&&word[0]<=90&&word[1]<=90) {return false;} //AB
            if(word[0]>=97&&word[1]<=90) {return false;} //aB
            if(word[i]<=90&&word[0]<=90&&word[1]>=97) {return false;} //Ab
            if(word[i]<=90&&word[0]>=97&&word[1]>=97) {return false;} //ab
        }
        return true;
    }
};

2.相对好些的做法

交替比较,每两个相邻的字母进行比较,除去个别地方,一大一小或一小一大必为无效单词。

class Solution {
public:
    bool detectCapitalUse(string word) {
        for(int i = 1; i < word.size(); i++)
        {
            if(isupper(word[i]) && islower(word[i-1]))
                return false;
            if(islower(word[i]) && isupper(word[i-1]) && i!=1)
                return false;
        }
        return true;
    }
};

本文虽拙,却也系作者劳动,转载还请保留本文链接: http://cyleft.com/?p=386



Have any Question or Comment?

发表评论

电子邮件地址不会被公开。 必填项已用*标注