快站 淘宝优惠券,企业建设网站策划案,锡林郭勒盟建设局网站,网络营销方法的分析与应用5918. 统计字符串中的元音子字符串
子字符串 是字符串中的一个连续#xff08;非空#xff09;的字符序列。
元音子字符串 是 仅 由元音#xff08;‘a’、‘e’、‘i’、‘o’ 和 ‘u’#xff09;组成的一个子字符串#xff0c;且必须包含 全部五种 元音。
给你一个字…5918. 统计字符串中的元音子字符串
子字符串 是字符串中的一个连续非空的字符序列。
元音子字符串 是 仅 由元音‘a’、‘e’、‘i’、‘o’ 和 ‘u’组成的一个子字符串且必须包含 全部五种 元音。
给你一个字符串 word 统计并返回 word 中 元音子字符串的数目 。
示例 1输入word aeiouu
输出2
解释下面列出 word 中的元音子字符串斜体加粗部分
- aeiouu
- aeiouu示例 2输入word unicornarihan
输出0
解释word 中不含 5 种元音所以也不会存在元音子字符串。示例 3输入word cuaieuouac
输出7
解释下面列出 word 中的元音子字符串斜体加粗部分
- cuaieuouac
- cuaieuouac
- cuaieuouac
- cuaieuouac
- cuaieuouac
- cuaieuouac
- cuaieuouac示例 4输入word bbaeixoubb
输出0
解释所有包含全部五种元音的子字符串都含有辅音所以不存在元音子字符串。提示
1 word.length 100word 仅由小写英文字母组成
解题思路
遍历word所有的子串检查每个子串中是否只包含全部五种 元音。
代码
class Solution {
public:int countVowelSubstrings(string word) {int res 0;for (int i 0; i 5 word.size(); i) {for (int j i 5; j word.size(); j) {if (judge(word, i, j))res;}}return res;}bool judge(string s, int l, int r) {bool a(false), e(false), i(false), o(false), u(false);for (int j l; j r; j) {if (s[j] a)a true;else if (s[j] i)i true;else if (s[j] o)o true;else if (s[j] u)u true;else if (s[j] e)e true;else return false;}return a i o u e;}
};优化解题思路
遍历所有子串时我们固定起始字符遍历以该字符为起点的长度大于5的字符串如果查找到了满足条件的子串则直接向后查找连续的元音字母如果可以查找到则说明可以加入一个新的满足条件的子串一旦遍历到非元音字母则中止对长度的遍历
代码
class Solution {
public:int countVowelSubstrings(string word) {int res 0;unordered_setchar set{a, i, o, u, e};for (int i 0; i 5 word.size(); i) {for (int j i 5; j word.size(); j) {if (judge(word, i, j)) {res;while (j word.size() set.find(word[j]) ! set.end()){res;j;}break;}}}return res;}bool judge(string s, int l, int r) {bool a(false), e(false), i(false), o(false), u(false);for (int j l; j r; j) {if (s[j] a)a true;else if (s[j] i)i true;else if (s[j] o)o true;else if (s[j] u)u true;else if (s[j] e)e true;else return false;}return a i o u e;}
};