直接列出题目如下:
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".
只要单词是正确的格式即可,且题目也已确认不会输入其他字符,所以对输入的单词每个字母进行遍历。代码如下:
bool detectCapitalUse(string word) {
if (word[0] >= 'A' && word[0] <= 'Z') {
if (word.length() > 1) {
if (word[1] > 'Z') {
for (int k = 2; k < word.length(); k++) {
if (word[k] <= 'Z')
return false;
}
}
else if(word[1] <= 'Z') {
for (int k = 2; k < word.length(); k++) {
if (word[k] > 'Z')
return false;
}
}
}
}
else if (word[0] >= 'a' && word[0] <= 'z') {
for (int i = 0; i < word.length(); i++) {
if (word[i] < 'a' || word[i] > 'z')
return false;
}
}
return true;
}
if (word[0] >= 'A' && word[0] <= 'Z') {
if (word.length() > 1) {
if (word[1] > 'Z') {
for (int k = 2; k < word.length(); k++) {
if (word[k] <= 'Z')
return false;
}
}
else if(word[1] <= 'Z') {
for (int k = 2; k < word.length(); k++) {
if (word[k] > 'Z')
return false;
}
}
}
}
else if (word[0] >= 'a' && word[0] <= 'z') {
for (int i = 0; i < word.length(); i++) {
if (word[i] < 'a' || word[i] > 'z')
return false;
}
}
return true;
}