Detect Capital
Problem
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, like
"Google"
.
Given a string word
, return true
if the usage of capitals in it is right.
Constraints
1 <= word.length <= 100
word
consists of lowercase and uppercase English letters.
Solution
The problem Detect Capital
can be solved by simply comparing letter cases character by character. To improve performance, problem logic can be simplified a bit. Based on the problem description, all characters other than the first need to have a matching letter case. If they all match and the first letter is a capital, then the given string properly uses capitals. If, on the other hand, the first letter is not a capital, then all other letters in the string needs to be lower case for the usage of capitals to be right. Therefore, the problem can be solved without using a variable to store the letter case of the first letter.
Implementation
class Solution
{
public:
bool detectCapitalUse(string word)
{
for (int i = 1; i < word.length() - 1; i++)
if (word[i] >= 97 != word[i + 1] >= 97)
return false;
return word.length() == 1 || word[0] <= 90 || (word[0] >= 97 == word[1] >= 97);
}
};