1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { private int modulo = 1000000007; private Integer[][] memo; private Map<Character, Integer> charIndex;
public int countVowelPermutation(int n) { int ans = 0; char[] vowels = new char[] { 'a', 'e', 'i', 'o', 'u' }; memo = new Integer[n][5]; charIndex = new HashMap<>(); for (int i = 0; i < vowels.length; i++) { charIndex.put(vowels[i], i); } for (char vowel : vowels) { ans = (ans % modulo + helper(n, 0, vowel) % modulo) % modulo; } return ans % modulo; }
private int helper(int n, int pos, char currChar) { int ans = 0, currCharIndex = charIndex.get(currChar); if (pos == n - 1) { return memo[pos][currCharIndex] = 1; } if (memo[pos][currCharIndex] != null) { return memo[pos][currCharIndex]; } if (currChar == 'a') { ans = (ans % modulo + helper(n, pos + 1, 'e') % modulo) % modulo; } else if (currChar == 'e') { ans = (ans % modulo + helper(n, pos + 1, 'a') % modulo + helper(n, pos + 1, 'i') % modulo) % modulo; } else if (currChar == 'i') { ans = (ans % modulo + helper(n, pos + 1, 'a') % modulo) % modulo; ans = (ans % modulo + helper(n, pos + 1, 'e') % modulo) % modulo; ans = (ans % modulo + helper(n, pos + 1, 'o') % modulo) % modulo; ans = (ans % modulo + helper(n, pos + 1, 'u') % modulo) % modulo; } else if (currChar == 'o') { ans = (ans % modulo + helper(n, pos + 1, 'i') % modulo) % modulo; ans = (ans % modulo + helper(n, pos + 1, 'u') % modulo) % modulo; } else if (currChar == 'u') { ans = (ans % modulo + helper(n, pos + 1, 'a') % modulo) % modulo; } return memo[pos][currCharIndex] = ans; } }
|