写在前面
- 简单逻辑处理
- 全大写、首字母大写逻辑整合
题目详情
给定一个单词,你需要判断单词的大写使用是否正确。
我们定义,在以下情况时,单词的大写用法是正确的:
全部字母都是大写,比如"USA"。
单词中所有字母都不是大写,比如"leetcode"。
如果单词不只含有一个字母,只有首字母大写, 比如 "Google"。
否则,我们定义这个单词没有正确使用大写字母。
示例 1:
输入: "USA"
输出: True
示例 2:
输入: "FlaG"
输出: False
注意:
ac代码
-
字符法
class Solution
{
public:
bool detectCapitalUse(string word)
{
int cnt = 0;
for(auto c : word)
{
if(c>='A' && c<='Z')
cnt++;
}
if(cnt == word.size() || cnt == 0)
return true;
else if(cnt==1 && (word[0]>='A' && word[0]<='Z'))
return true;
return false;
}
};
-
累积求和法
- 全大写:
fir+sum==0
- 首字母大写:
fir==0&&sum==sl-1
- 全小写:
fir+sum==sl
class Solution
{
public:
bool utlower(char i)
{
return i<='z'&&i>='a';
}
bool detectCapitalUse(string word)
{
int sl=word.size(),sum=0;
bool fir = utlower(word[0]);
for(int i=1; i<sl; i++)
sum += utlower(word[i]);
return (fir+sum==0) || (fir+sum==sl) || (fir==0&&sum==sl-1);
}
};
- 参考文章
- Leetcode刷题78-520. 检测大写字母(C++详细解法!!!)