题目:
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.
代码:
自己的:
class Solution {
public:
bool detectCapitalUse(string word) {
bool result = 1;
if (word[0] < 'a'){
if (word[1] < 'a'){
for(int i = 2; i < word.size(); i++){
if(word[i] > 'Z'){
result = 0;
break;
}
}
}
else{
for(int i = 2; i < word.size(); i++){
if(word[i] < 'a'){
result = 0;
break;
}
}
}
}
else{
for(auto c : word){
if (c < 'a'){
result = 0;
break;
}
}
}
return result;
}
};
别人的:
class Solution {
public:
bool detectCapitalUse(string word) {
int cnt = 0;
for(int a = 0; a < word.length(); a++ ) {
if('Z' - word[a] >= 0)
cnt++;
}
if(cnt == word.length() || cnt == 0 || (cnt == 1 && ('Z' - word[0] >= 0)))
return true;
return false;
}
};
对大写字母计数,然后再判断(全是大写、全是小写、首字母大写)