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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| class Solution { private static final int MOD = (int) 1e9 + 7;
public int numberOfWays(String s, String t, long k) { int n = s.length(); char[] text = (s + s.substring(0, n - 1)).toCharArray(); char[] pattern = t.toCharArray(); int c = kmp(text, pattern);
long[][] m = {{c - 1, c}, {n - c, n - c - 1}}; m = pow(m, k); return s.equals(t) ? (int) m[0][0] : (int) m[0][1]; }
private int kmp(char[] text, char[] pattern) { int m = text.length, n = pattern.length; int[] next = new int[n]; for (int i = 1, j = 0; i < n; i++) { while (j > 0 && pattern[i] != pattern[j]) { j = next[j - 1]; } if (pattern[i] == pattern[j]) j++; next[i] = j; }
int cnt = 0; for (int i = 0, j = 0; i < m; i++) { while (j > 0 && text[i] != pattern[j]) { j = next[j - 1]; } if (text[i] == pattern[j]) j++; if (j == n) { cnt++; j = next[j - 1]; } } return cnt; }
private long[][] pow(long[][] a, long n) { long[][] res = {{1, 0}, {0, 1}}; while (n != 0) { if ((n & 1) == 1) res = mul(res, a); a = mul(a, a); n >>= 1; } return res; }
private long[][] mul(long[][] a, long[][] b) { long[][] c = new long[2][2]; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { c[i][j] = (a[i][0] * b[0][j] + a[i][1] * b[1][j]) % MOD; } } return c; } }
|