Summary of Lituo solution 1641. Count the number of lexicographical vowel strings

 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:

Given an integer  n, return   the number of strings of length lexicographicallyn made up  of only vowels ( aeiou)  .

Strings  are s lexicographically  ordered  : for all valid  i, s[i] the position in the alphabet is always the  s[i+1] same as or  s[i+1] preceded by .

Example 1:

Input: n = 1
 Output: 5
 Explanation: The 5 lexicographic strings consisting only of vowels are["a","e","i","o","u"]

Example 2:

Input: n = 2
 Output: 15
 Explanation: The 15 lexicographic strings consisting only of vowels are
["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]
Note that "ea" is not a suitable string because 'e' is later in the alphabet than 'a'

Example 3:

Input: n = 33
 Output: 66045

hint:

  • 1 <= n <= 50 

Problem-solving ideas:

* Problem-solving ideas:
* This question is actually a dynamic programming question.
* We use a two-bit array ints to store the possibilities (arranged in lexicographical order) when the length is i and only allow (a, e, i, o, u) respectively.
* When the length is 1, the probability of all 5 natural vowels is 1.
* When the length is 2, put u first, then the last digit can only be u. So the possibility that the length is 2 and the first digit is u is 1; that is, ints[i][0]=ints[i-1][0]
* Similarly, so the length is 2 and the possibility of the first digit being o is 2; that is, ints[i][1]=ints[i-1][1]+ints[i-1][0]
* Similarly, so the length is 2 and the possibility of the first digit being i is 3; that is, ints[i][2]=ints[i-1][2]+...;
* Similarly, so the possibility of the length being 2 and the first digit being e is 4; that is, ints[i][3]=ints[i-1][3]+...;
* Similarly, so the length is 2 and the possibility of the first digit being a is 5; that is, ints[i][4]=ints[i-1][4]+...;
* If the length is 3, you can also continue according to the above theory, because if the first digit is u, then you can only choose the possibility that the second digit is also u.
* ints[3][0]=ints[2][0]
* ints[3][1]=ints[2][1]++ints[2][0];
* Finally, we can count the sum of the array ints[n-1].
 
 

code:

public class Solution1641 {

    public int countVowelStrings(int n) {
        int[][] ints = new int[n][5];
        Arrays.fill(ints[0], 1);
        for (int i = 1; i < n; i++) {
            int sum = 0;
            for (int j = 0; j < 5; j++) {
                sum += ints[i - 1][j];
                ints[i][j] = sum;
            }
        }
        return Arrays.stream(ints[n - 1]).sum();
    }
}

Guess you like

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