原题
原题链接
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
分析
判断大小写又没有用错正确的用法分为三种情况:
1.全小写
2.首字母大写
3.全大写
我的思路是判断首字母大小写的情况,如果是小写,则后面再出现一个大写就return false
如果首字母是大写,则count一下后面大写的个数,后面大写的个数如果是0则是首字母大写的情况,如果是word.size()-1
则表示全大写的情况。
代码
bool islower(const char& c)
{
if(c<='z'&&c>='a')
return true;
else
return false;
}
class Solution {
public:
bool detectCapitalUse(string word) {
if(islower(word[0]))
{
for(int i = 1;i<word.size();++i)
{
if(!islower(word[i]))
return false;
}
}
else
{
int count = 1;
for(int i = 1;i<word.size();++i)
{
if(!islower(word[i]))
++count;
}
return ((count==1)||(count==word.size()))?true:false;
}
return true;
}
};