[leetcode]520. Detect Capital
Analysis
Men are not good if they are not bad—— [ummmm~]
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.
这题主要是字母大小写的问题。
Implement
方法一
第一种情况,如果第一个字符是小写的,那么后面所有的字符都必须要是小写的;
第二种情况,如果第一个字符是大写的,那么要么后面所有的字符都是小写的,要么后面所有的字符都是大写的。
class Solution {
public:
bool detectCapitalUse(string word) {
int len = word.length();
if(islower(word[0])){
for(int i=1; i<len; i++){
if(isupper(word[i]))
return false;
}
return true;
}
else if(isupper(word[0])){
bool hasupper = false;
bool haslower = false;
for(int i=1; i<len; i++){
if(isupper(word[i]))
hasupper = true;
if(islower(word[i]))
haslower = true;
}
if(hasupper && haslower)
return false;
return true;
}
}
};
方法二
把字符串全部转换成大写得到字符串up,然后把字符串全部转换成小写low,如果原字符串和up相等或者跟low相等,则合法;当原字符串第一个字符大写时,如果后面所有的字符都是大写或者都是小写时,合法。
class Solution {
public:
bool detectCapitalUse(string word) {
int len = word.length();
string up = "";
string low = "";
for(auto c:word)
up += toupper(c);
for(auto c:word)
low += tolower(c);
if(word == up || word == low)
return true;
if(isupper(word[0])){
string t = word.substr(1, len-1);
string t1 = up.substr(1, len-1);
string t2 = low.substr(1, len-1);
if(t == t1 || t == t2)
return true;
}
return false;
}
};
方法三
利用正则表达式进行判断
class Solution {
public:
bool detectCapitalUse(string word) {
return regex_match(word, regex("[A-Z]+|[a-z]+|[A-Z][a-z]*"));
}
};