Detect Capital – LeetCode 520
Problem
Description
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.
Answer
Original
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public: bool detectCapitalUse(string word) { if(word[0] <= 'z' && word[0] >= 'a'){ for(auto p = word.cbegin(); p != word.cend(); ++p){ if(*p <= 'Z' && *p >= 'A') return false; } return true; } else { if(word.size() == 1) return true; if(word[1] <= 'z' && word[1] >= 'a'){ for(auto p = word.cbegin()+1; p != word.cend(); ++p){ if(*p <= 'Z' && *p >= 'A') return false; } return true; } else { for(auto p = word.cbegin()+1; p != word.cend(); ++p){ if(*p <= 'z' && *p >= 'a') return false; } return true; } } } };
|
思路
简单的枚举情况。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$15$ ms,排名$42.53\%$
Better
思路
漂亮的枚举反面情况。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$13$ ms,排名$22.82\%$
Code
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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; } };
|