标签:lag 说明 必须 ctc 串匹配 情况 lse beat bool
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:
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.
bool detectCapitalUse(string word)
1、这道题目不难,其实就是判断单词的形式合不合法。题目给定了几个判断条件:
如果全部字母都是大写,那么合法。如USA
如果全部字母都是小写,那么合法。如leetcode
如果单词超过一个字符,且首字母大写,其余字母小写,那么合法。如Google
2、明白条件之后,我们来写判断语句。
代码如下:
    bool detectCapitalUse(string word) 
    {
        bool flag=1;
        if(word.size()==1)//边界条件
            return true;
        if(islower(word[1]))//第二个字母是小写,之后必须都是小写
        {
            for(int i=2;i<word.size();i++)
            {
                if(isupper(word[i]))
                {
                    flag=0;
                    break;
                }
            }
            if(flag==0)
                return false;
            else 
                return true;//无论首字母大小写均合法
        }
        else 
        {
            for(int i=2;i<word.size();i++)//第二个字母大写,其后必须大写
            {
                if(islower(word[i]))
                {
                    flag=0;
                    break;
                }
            }
            if(flag==0)
                return false;
            if(isupper(word[0]))//首字母大写,合法
                return true;
            else
                return false;//首字母小写,不合法
        }
        
    }
上述代码囊括了所有的判断情况,实测15ms,beats 57.47% of cpp submissions。
3、在讨论区中看到有人用了字符串匹配的方法来做这道题,只写了一行代码,但是实测效果很慢……
标签:lag 说明 必须 ctc 串匹配 情况 lse beat bool
原文地址:https://www.cnblogs.com/king-3/p/8973174.html