- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 78 lines of Java from the credited upstream file 2851.java.
- The implementation visibly relies on sequence storage, cached states.
- 4 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public int numberOfWays(String s, String t, long k) {21 final int n = s.length();22 final int negOnePowK = (k % 2 == 0 ? 1 : -1); 23 final int[] z = zFunction(s + t + t);24 final List<Integer> indices = getIndices(z, n);25 int[] dp = new int[2]; 26 dp[1] = (int) ((modPow(n - 1, k) - negOnePowK + MOD) % MOD * modPow(n, MOD - 2) % MOD);27 dp[0] = (int) ((dp[1] + negOnePowK + MOD) % MOD);28 int ans = 0;29 for (final int index : getIndices(z, n)) {30 ans += dp[index == 0 ? 0 : 1];31 ans %= MOD;32 }33 return ans;34 }35 36 private static final int MOD = 1_000_000_007;37 38 private long modPow(long x, long n) {39 if (n == 0)40 return 1;41 if (n % 2 == 1)42 return x * modPow(x, n - 1) % MOD;43 return modPow(x * x % MOD, n / 2);44 }45 46 47 48 49 50 private int[] zFunction(final String s) {51 final int n = s.length();52 int[] z = new int[n];53 int l = 0;54 int r = 0;55 for (int i = 1; i < n; ++i) {56 if (i < r)57 z[i] = Math.min(r - i, z[i - l]);58 while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))59 ++z[i];60 if (i + z[i] > r) {61 l = i;62 r = i + z[i];63 }64 }65 return z;66 }67 68 69 70 private List<Integer> getIndices(int[] z, int n) {71 List<Integer> indices = new ArrayList<>();72 for (int i = n; i < n + n; ++i)73 if (z[i] >= n)74 indices.add(i - n);75 return indices;76 }77}78