classSolution: deflongestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int: s = set() for x in arr1: c = str(x) n = len(c) for i inrange(1, n + 1): s.add(c[:i]) ans = 0 for x in arr2: c = str(x) n = len(c) for i inrange(1, n + 1): if c[:i] in s: ans = max(ans, i) return ans
defis_prime(x: int) -> bool: if x < 2: returnFalse k = 2 while k * k <= x: if x % k == 0: returnFalse k += 1 returnTrue
n, m = len(mat), len(mat[0]) d = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] for i inrange(n): for j inrange(m): if mat[i][j] > 10and is_prime(mat[i][j]): cnt[mat[i][j]] += 1 for dx, dy in d: sx, sy, t = i, j, mat[i][j] while0 <= sx + dx < n and0 <= sy + dy < m: sx, sy = sx + dx, sy + dy t = t * 10 + mat[sx][sy] if t > 10and is_prime(t): cnt[t] += 1 ans, mxv = -1, 0 for k, v in cnt.items(): if v > mxv or v == mxv and k > ans: ans = k mxv = v return ans
longget(String s, int[] z) { Nodetemp= root; longret=0; intn= s.length(); char[] chars = s.toCharArray(); for (inti=0; i < n; i++) { intc= chars[i] - 'a'; if (temp.nodes[c] == null) return ret; if (i == n - 1 || z[n - i - 1] == i + 1) ret += temp.nodes[c].cnt; temp = temp.nodes[c]; } return ret; }
publiclongcountPrefixSuffixPairs(String[] words) { List<int[]> list = sHash(words);
longans=0; for (inti=0; i < words.length; i++) { ans += get(words[i], list.get(i)); add(words[i]); } return ans; }
public List<int[]> zFunc(String[] words) { List<int[]> zList = newArrayList<>(); for (String string : words) { char[] s = string.toCharArray(); intn= s.length; int[] z = newint[n]; for (inti=1, l = 0, r = 0; i < n; ++i) { if (i <= r && z[i - l] < r - i + 1) { z[i] = z[i - l]; } else { z[i] = Math.max(0, r - i + 1); while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i]; } if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } zList.add(z); } return zList; }
public List<int[]> sHash(String[] words) { List<int[]> list = newArrayList<>(); intP=233; for (var word : words) { intn= word.length(); int[] p = newint[n + 1], h = newint[n + 1]; p[0] = 1; for (inti=1; i <= n; i++) { p[i] = p[i - 1] * P; h[i] = h[i - 1] * P + word.charAt(i - 1); } int[] k = newint[n]; for (inti=1; i < n; i++) { if (h[n] - h[i] * p[n - i] == h[n - i] - h[0] * p[n - i]) k[i] = n - i; //和z函数保持一致 } list.add(k); } return list; } }