Day 11:2559. 统计范围内的元音字符串数

78 阅读1分钟

Leetcode 2559. 统计范围内的元音字符串数

给你一个下标从 0 开始的字符串数组 words 以及一个二维整数数组 queries 。 每个查询 queries[i] = [li, ri] 会要求我们统计在 words 中下标在 li 到 ri 范围内(包含 这两个值)并且以元音开头和结尾的字符串的数目。 返回一个整数数组,其中数组的第 i 个元素对应第 i 个查询的答案。 **注意:**元音字母是 'a'、'e'、'i'、'o' 和 'u' 。

image.png

首先判断是不是元音字符串,使用正则表达式进行判断:

Pattern compile = Pattern.compile("^[aeiou].*[aeiou]$|[aeiou]");
boolean match = compile.matcher(words[i]).matches();

用一个数组保存每个字符串是不是元音字符串。
用一个 dp[i][j] 数组保存从 i 到 j 范围内(包括 i 和 j)元音字符串的结果,也就是每次从查询范围内遍历一次计算结果。这是以空间换时间的方法。

完整代码

import java.util.regex.Pattern;

class Solution {
    public int[] vowelStrings(String[] words, int[][] queries) {
        int n = words.length;
        boolean[] tag = new boolean[n];
        Pattern compile = Pattern.compile("^[aeiou].*[aeiou]$|[aeiou]");
        for (int i = 0; i < n; i++) {
            tag[i] = compile.matcher(words[i]).matches();
        }
        int[][] dp = new int[n][n];
        for (int i = 0; i < n; i++) {
            int count = 0;
            if (tag[i]) {
                count++;
                dp[i][i] = 1;
            }
            for (int j = i + 1; j < n; j++) {
                if (tag[j]) count++;
                dp[i][j] = count;
            }
        }
        
        int m = queries.length;
        int[] res = new int[m];
        for (int i = 0; i < m; i++) {
            res[i] = dp[queries[i][0]][queries[i][1]];
        }
        return res;
    }
}

以上方法未通过最后一个测试用例。内存超出时间限制,还需优化。

实际上 dp 数组只使用了上三角的部分,可以使用一维数组存储二维数组上三角部分的值。