寫在前面
題目詳情
給定一個單詞,你需要判斷單詞的大寫使用是否正確。
我們定義,在以下情況時,單詞的大寫用法是正確的:
全部字母都是大寫,比如"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);
}
};