1. 程式人生 > >leetcode-520-Detect Capital

leetcode-520-Detect Capital

ons emp ctc con miss 很慢 字符 other 都是

題目描述:

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.

要完成的函數:

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、在討論區中看到有人用了字符串匹配的方法來做這道題,只寫了一行代碼,但是實測效果很慢……

leetcode-520-Detect Capital