简单的string问题解决:Detect Capital

来源:互联网 发布:怎么打理淘宝店铺 编辑:程序博客网 时间:2024/05/21 17:13

直接列出题目如下:

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:

  1. All letters in this word are capitals, like "USA".
  2. All letters in this word are not capitals, like "leetcode".
  3. 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.

只要单词是正确的格式即可,且题目也已确认不会输入其他字符,所以对输入的单词每个字母进行遍历。代码如下:

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;
}
0 0