Leetcode3136. 有效单词

Every day a Leetcode

题目来源:3136. 有效单词

解法1:模拟

算法:

  1. 首先判断字符串 word 的长度,小于 3 则返回 false。
  2. word 只由数字 0-9 和英文大小写字母组成,发现其他字符返回 false。
  3. digit 标识数字有没有出现过,upper 和 lower 分别标识大写字母和小写字母有没有出现过,cntYuan 和 cntNotYuan 分别统计元音字母和辅音字母的个数。
  4. 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)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值