LeetCode Detect Capital
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.
判断一个单词的大写形式是否正确,大写的规则有三:
- 所有字母都是大写
- 所有字母都是小写
- 首字母大写,剩余字母全小写
简单题,直接根据规则写代码就好。如果首字母是小写,则剩余字母要全是小写。如果首字母是大写,则剩余字母要么都是大写,要么都是小写。
代码如下:
[cpp]
class Solution {
private:
inline bool myisupper(const char& c) {
return c >= ‘A’&&c <= ‘Z’;
}
public:
bool detectCapitalUse(string word) {
int n = word.size();
if (n == 1)return true;
bool firstUpper = myisupper(word[0]);
if (firstUpper) {
bool second = myisupper(word[1]);
for (int i = 2; i < n; ++i) {
if (second != myisupper(word[i]))return false;
}
return true;
}
else {
for (int i = 1; i < n; ++i) {
if (myisupper(word[i]))return false;
}
return true;
}
}
};
[/cpp]
本代码提交AC,用时12MS。
奇怪的是,我用系统的isupper遇到“USA”单词时会判断错误,但是用自己实现的myisupper就好了。
网上还有一种简洁的方法,统计单词中大写字母的个数upper_cnt,如果upper_cnt==0,说明全是小写,正确;如果upper_cnt==n,说明全是大写,正确;如果upper_cnt==1,且首字母是大写,也是正确;其他情况都是错误。逻辑清楚,代码简洁:
[cpp]
class Solution {
public:
bool detectCapitalUse(string word) {
int n = word.size(), upper_cnt = 0;
for (int i = 0; i < n; ++i) {
if (isupper(word[i]))++upper_cnt;
}
if (upper_cnt == 0 || n == upper_cnt)return true;
if (upper_cnt == 1 && isupper(word[0]))return true;
return false;
}
};
[/cpp]
本代码提交AC,用时6MS。]]>