都发嘎嘎
# 测试代码块
# test code block
print("hello world!")
C++PythonJava
vector<int> prefix_function(string s) {
int n = (int)s.length();
vector<int> pi(n);
for (int i = 1; i < n; i++)
for (int j = pi[i - 1] + 1; j >= 0; j--) // improved: j=i => j=pi[i-1]+1
if (s.substr(0, j) == s.substr(i - j + 1, j)) {
pi[i] = j;
break;
}
return pi;
}
def prefix_function(s):
n = len(s)
pi = [0] * n
for i in range(1, n):
for j in range(pi[i - 1] + 1, -1, -1):
if s[0 : j] == s[i - j + 1 : i + 1]:
pi[i] = j
break
return pi
public class PrefixFunction {
public int[] prefixFunction(String s) {
int n = s.length();
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
for (int j = pi[i - 1]; j >= 0; j--) {
if (s.substring(0, j).equals(s.substring(i - j + 1, i + 1))) {
pi[i] = j;
break;
}
}
}
return pi;
}
}
证明过程
using std::string;
const int M = 1e9 + 7;
const int B = 233;
typedef long long ll;
int get_hash(const string& s) {
int res = 0;
for (int i = 0; i < s.size(); ++i) {
res = ((ll)res * B + s[i]) % M;
}
return res;
}
bool cmp(const string& s, const string& t) {
return get_hash(s) == get_hash(t);
}