Every day a leetcode
题目来源:520. 检测大写字母
解法1:
根据题目要求,若单词的大写用法正确,则需要满足:
-
若第 1 个字母为大写,则其他字母必须均为大写或均为小写;
-
若第 1 个字母为小写,则其他字母必须均为小写。
遍历一次字符串就能得到答案。
代码:
/*
* @lc app=leetcode.cn id=520 lang=cpp
*
* [520] 检测大写字母
*/
// @lc code=start
class Solution
{
public:
bool detectCapitalUse(string word)
{
if (word.size() <= 1)
return true;
if (isupper(word[0]))
{
if (isupper(word[1]))
{
for (int i = 2; i < word.size(); i++)
if (islower(word[i]))
return false;
}
else
{
for (int i = 2; i < word.size(); i++)
if (isupper(word[i]))
return false;
}
}
else
{
for (int i = 1; i < word.size(); i++)
if (isupper(word[i]))
return false;
}
return true;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(n),其中 n 为字符串的长度。我们需要遍历字符串中的每个字符。
空间复杂度:O(1)。