520. Detect Capital【easy】
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) {
if (word.length() <= ) {
return true;
} bool flag = false;
for (int i = ; i < word.length(); ++i) {
//以小写字母开头,则后面都必须为小写
if (word[] >= 'a' && word[] <= 'z') {
if (word[i] < 'a' || word[i] > 'z') {
return false;
}
}
//以大写字母开头,下面分类讨论
else if (word[] >= 'A' && word[] <= 'Z') {
if (i == && word[i] >= 'a' && word[i] <= 'z') {
flag = true;
continue;
}
//说明后面都必须为小写
if (flag) {
if (word[i] >= 'A' && word[i] <= 'Z') {
return false;
}
}
//说明后面都必须为大写
else {
if (word[i] >= 'a' && word[i] <= 'z') {
return false;
}
}
}
} return true;
}
};
解法二:
class Solution {
public:
bool detectCapitalUse(string word) {
int size=word.size(),count=;
if(size<=)
return true;
for (int i = ; i < size; i++){
if(word[i]>='a'&&word[i]<='z')
count+=;
else
count+=;
}
if(count==size-)
return true;
else if(count==*(size-))
return word[]>='A'&&word[]<='Z';
else
return false;
}
};
参考@zhengchaojie 的代码。
From 1~size-1,if we meet with a-z,we add 1,else we add 2.Then we can get the result that if the second to last letter is all lowercase or all upcase.
解法三:
bool detectCapitalUse(string word) {
const char *c = word.c_str();
if (word.size() <= ) return true;
if (*c <= 'z' && *c >= 'a') {
c = c + ;
while (*c) {
if (*c <= 'Z' && *c >= 'A') return false;
c = c + ;
}
} else {
c = c + ;
if (*c <= 'Z' && *c >= 'A') {
c = c + ;
while (*c) {
if (*c <= 'z' && *c >= 'a') return false;
c = c + ;
}
} else {
c = c + ;
while (*c) {
if (*c <= 'Z' && *c >= 'A') return false;
c = c + ;
}
}
} return true;
}
参考@ai977313677 的代码。
解法四:
class Solution {
public:
bool detectCapitalUse(string word) {
int cnt = ;
for (char c : word) if (isupper(c)) ++cnt;
return !cnt || cnt == word.size() || cnt == && isupper(word[]);
}
};
参考@lzl124631x 的代码。