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:
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 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:
Example 2:
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
這道題給了我們一個單詞,讓我們檢測大寫格式是否正确,規定了三種正确方式,要麼都是大寫或小寫,要麼首字母大寫,其他情況都不正确。那麼我們要做的就是統計出單詞中所有大寫字母的個數cnt,再來判斷是否屬于這三種情況,如果cnt為0,說明都是小寫,正确;如果cnt和單詞長度相等,說明都是大寫,正确;如果cnt為1,且首字母為大寫,正确,其他情況均傳回false,參見代碼如下:
解法一:
下面這種方法利用了STL的内置方法count_if,根據條件來計數,這樣使得code非常簡潔,兩行就搞定了,喪心病狂啊~
解法二: