5918. 统计字符串中的元音子字符串

376 阅读1分钟

这是我参与11月更文挑战的第6天,活动详情查看:2021最后一次更文挑战

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;
    }
};