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:
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.
這道題給了我們一個單詞,讓我們檢測大寫格式是否正確,規定了三種正確方式,要么都是大寫或小寫,要么首字母大寫,其他情況都不正確。那么我們要做的就是統計出單詞中所有大寫字母的個數cnt,再來判斷是否屬於這三種情況,如果cnt為0,說明都是小寫,正確;如果cnt和單詞長度相等,說明都是大寫,正確;如果cnt為1,且首字母為大寫,正確,其他情況均返回false,參見代碼如下:
解法一:
class Solution { public: bool detectCapitalUse(string word) { int cnt = 0, n = word.size(); for (int i = 0; i < n; ++i) { if (word[i] <= 'Z') ++cnt; } return cnt == 0 || cnt == n || (cnt == 1 && word[0] <= 'Z'); } };
下面這種方法利用了STL的內置方法count_if,根據條件來計數,這樣使得code非常簡潔,兩行就搞定了,喪心病狂啊~
解法二:
class Solution { public: bool detectCapitalUse(string word) { int cnt = count_if(word.begin(), word.end(), [](char c){return c <= 'Z';}); return cnt == 0 || cnt == word.size() || (cnt == 1 && word[0] <= 'Z'); } };
參考資料:
https://discuss.leetcode.com/topic/79912/3-lines
https://discuss.leetcode.com/topic/79930/java-1-liner
https://discuss.leetcode.com/topic/80314/6ms-2-lines-c-solution/2
https://discuss.leetcode.com/topic/79911/simple-java-solution-o-n-time-o-1-space