题目:
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".
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.
思路:
练手题目。不过不知道为啥,我在VS下面用isupper函数来判断word[i]是不是大写字母,可以通过对“USA”这个例子的测试;然而在Leetcode测试平台上,却只能用来(word[i] >= 'A' && word[i] <= 'Z')测试才行。这是不是Leetcode测试平台上的一个小bug?知道原因的读者请留言。。。
代码:
class Solution {
public:
bool detectCapitalUse(string word) {
if (word.length() == 1) {
return true;
}
else {
bool first_upper = word[0] >= 'A' && word[0] <= 'Z';
bool second_upper = word[1] >= 'A' && word[1] <= 'Z';
bool right_case = first_upper ? second_upper : false;
for (int i = 1; i < word.length(); ++i) {
if ((word[i] >= 'A' && word[i] <= 'Z') != right_case) {
return false;
}
}
return true;
}
}
};