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 <= 100
- word 僅由小寫英文字母組成
解題思路
遍歷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_set<char> 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;}
};