classSolution { public: string shortestPalindrome(string s){ int n = s.size(); int base = 131, mod = 1000000007; int left = 0, right = 0, mul = 1; int best = -1; for (int i = 0; i < n; ++i) { left = ((longlong)left * base + s[i]) % mod; right = (right + (longlong)mul * s[i]) % mod; if (left == right) { best = i; } mul = (longlong)mul * base % mod; } string add = (best == n - 1 ? "" : s.substr(best + 1, n)); reverse(add.begin(), add.end()); return add + s; } };
classSolution { public String shortestPalindrome(String s) { intn= s.length(); intbase=131, mod = 1000000007; intleft=0, right = 0, mul = 1; intbest= -1; for (inti=0; i < n; ++i) { left = (int) (((long) left * base + s.charAt(i)) % mod); right = (int) ((right + (long) mul * s.charAt(i)) % mod); if (left == right) { best = i; } mul = (int) ((long) mul * base % mod); } Stringadd= (best == n - 1 ? "" : s.substring(best + 1)); StringBufferans=newStringBuffer(add).reverse(); ans.append(s); return ans.toString(); } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution: defshortestPalindrome(self, s: str) -> str: n = len(s) base, mod = 131, 10**9 + 7 left = right = 0 mul = 1 best = -1 for i inrange(n): left = (left * base + ord(s[i])) % mod right = (right + mul * ord(s[i])) % mod if left == right: best = i mul = mul * base % mod add = (""if best == n - 1else s[best+1:]) return add[::-1] + s
char* shortestPalindrome(char* s) { int n = strlen(s); int base = 131, mod = 1000000007; int left = 0, right = 0, mul = 1; int best = -1; for (int i = 0; i < n; ++i) { left = ((longlong)left * base + s[i]) % mod; right = (right + (longlong)mul * s[i]) % mod; if (left == right) { best = i; } mul = (longlong)mul * base % mod; } int ret_len = n - best - 1; char* ret = malloc(sizeof(char) * (ret_len + n + 1)); for (int i = 0; i < ret_len; i++) ret[i] = s[n - i - 1]; for (int i = 0; i < n; i++) ret[i + ret_len] = s[i]; ret[ret_len + n] = 0; return ret; }
funcshortestPalindrome(s string)string { n := len(s) base, mod := 131, 1000000007 left, right, mul := 0, 0, 1 best := -1 for i := 0; i < n; i++ { left = (left * base + int(s[i] - '0')) % mod right = (right + mul * int(s[i] - '0')) % mod if left == right { best = i } mul = mul * base % mod } add := "" if best != n - 1 { add = s[best + 1:] } b := []byte(add) for i := 0; i < len(b) / 2; i++ { b[i], b[len(b) - 1 -i] = b[len(b) - 1 -i], b[i] } returnstring(b) + s }