Every day a Leetcode
题目来源:3136. 有效单词
解法1:模拟
算法:
- 首先判断字符串 word 的长度,小于 3 则返回 false。
- word 只由数字 0-9 和英文大小写字母组成,发现其他字符返回 false。
- digit 标识数字有没有出现过,upper 和 lower 分别标识大写字母和小写字母有没有出现过,cntYuan 和 cntNotYuan 分别统计元音字母和辅音字母的个数。
- return (digit || upper || lower) && cntYuan > 0 && cntNotYuan > 0 即可。
代码:
class Solution
{
private:
bool isYuan(char &c)
{
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
return true;
else if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
return true;
return false;
}
public:
bool isValid(string word)
{
if (word.length() < 3)
return false;
bool digit = false, upper = false, lower = false;
int cntYuan = 0, cntNotYuan = 0;
for (char &c : word)
{
if (isdigit(c))
digit = true;
else if (isupper(c))
upper = true;
else if (islower(c))
lower = true;
else
return false;
if (isYuan(c))
cntYuan++;
if ((isupper(c) || islower(c)) && !isYuan(c))
cntNotYuan++;
}
return (digit || upper || lower) && cntYuan > 0 && cntNotYuan > 0;
}
};
结果:
复杂度分析:
时间复杂度:O(n),其中 n 是字符串 word 的长度。
空间复杂度:O(1)。