LeetCode 1641: Count Sorted Vowel Strings
Problem Description
Explanation
To solve this problem, we can use dynamic programming. We can maintain a 2D array dp
where dp[i][j]
represents the number of valid strings of length i+1
ending with the vowel at index j
(0-indexed) in the vowels array ['a', 'e', 'i', 'o', 'u']
. We can calculate the values in the dp
array iteratively based on the previous values.
At each step, the number of valid strings ending with a vowel at index j
is the sum of the number of valid strings ending with a vowel at index j
or any vowel before it. This is because the strings are required to be lexicographically sorted.
Finally, we sum up the values in the last row of the dp
array to get the total number of valid strings of length n
.
Time complexity: O(n)
Space complexity: O(5n) = O(n)
Solutions
class Solution {
public int countVowelStrings(int n) {
int[][] dp = new int[n][5];
for (int i = 0; i < 5; i++) {
dp[0][i] = 1;
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < 5; j++) {
for (int k = 0; k <= j; k++) {
dp[i][j] += dp[i-1][k];
}
}
}
int result = 0;
for (int i = 0; i < 5; i++) {
result += dp[n-1][i];
}
return result;
}
}
Loading editor...