LeetCode solution summary 2559. The number of vowel strings in the statistical range

Directory link:

Lituo Programming Problems - Summary of Solutions_Share+Records-CSDN Blog

GitHub synchronous brushing project:

https://github.com/September26/java-algorithms

Link to the original title: Likou


describe:

You are given a zero-based  array  of strings  words and a two-dimensional array of integers  queries .

Each query  queries[i] = [li, ri] will ask us to count   the number of strings in which the middle words subscript is in  li the  ri range ( inclusive ) and start and end with a vowel.

Returns an array of integers where the th  i element of the array corresponds to  i the answer to the th query.

Note: The vowels are  'a', 'e', 'i', 'o' and  'u' .

Example 1:

Input: words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]] Output
 : [ 2,3,0]
 Explanation: The strings that start and end with vowels are "aba", "ece", "aa" and "e".
The query [0,2] results in 2 (the strings "aba" and "ece").
The query [1,4] results in 3 (the strings "ece", "aa", "e").
The query [1,1] results in 0.
Returns the result [2,3,0].

Example 2:

Input: words = ["a","e","i"], queries = [[0,2],[0,1],[2,2]]
 Output: [3,2,1]
 Explanation: Every string satisfies this condition, so [3,2,1] is returned.

hint:

  • 1 <= words.length <= 105
  • 1 <= words[i].length <= 40
  • words[i] Consists of lowercase English letters only
  • sum(words[i].length) <= 3 * 105
  • 1 <= queries.length <= 105
  • 0 <= queries[j][0] <= queries[j][1] < words.length

Problem-solving ideas:

* Problem-solving ideas:
* This question can easily find out which of the words meets the requirements and which does not. But the difficulty is that the range of queries is not 10^5, and the length of words is also 10^5, so the time complexity of O(n) must be guaranteed.
* So we can use the prefix sum method to calculate, use the array prefixs to record the sum of all the required quantities before each digit in words.
* In this way, the answer to queries[i] is prefixs[li]-prefixs[ri]

code:

public class Solution2559 {
    Set<String> set = new HashSet<>();
    public int[] vowelStrings(String[] words, int[][] queries) {
        set.add("a");
        set.add("e");
        set.add("i");
        set.add("o");
        set.add("u");
        int sum = 0;
        int[] prefixs = new int[words.length + 1];
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            if (set.contains(word.substring(0, 1)) && set.contains(word.substring(word.length() - 1))) {
                sum++;
            }
            prefixs[i + 1] = sum;
        }
        int[] result = new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int[] query = queries[i];
            result[i] = prefixs[query[1] + 1] - prefixs[query[0]];
        }
        return result;
    }
}

Guess you like

Origin blog.csdn.net/AA5279AA/article/details/131002916