[英]Given an integer K and a matrix of size t x t. construct a string s consisting of first t lowercase english letters such that the total cost of s is K
[英]Given two string S and T. Determine a substring of S that has minimum difference with T?
我有两个字符串S
和T
,其中S
>= T
的长度。 我必须确定S
的 substring 的长度与T
相同并且与T
的差异最小。 在这里,相同长度的两个字符串之间的差异意味着它们不同的索引数量。 例如: "ABCD"
和"ABCE"
在第 3 个索引处不同,因此它们的差异为 1。
我知道我可以使用 KMP(Knuth Morris Pratt) 模式搜索算法在 S 中搜索 T。但是,如果 S 不包含 T 作为 substring 怎么办? 所以,我编写了一个蛮力方法来解决这个问题:
int main() {
string S, T;
cin >> S >> T;
int SZ_S = S.size(), SZ_T = T.size(), MinDifference = INT_MAX;
string ans;
for (int i = 0; i + SZ_T <= SZ_S; i++) { // I generate all the substring of S
int CurrentDifference = 0; // and check their difference with T
for (int j = 0; j < SZ_T; j++) { // and store the substring with minimum difference
if (S[i + j] != T[j])
CurrentDifference++;
}
if (CurrentDifference < MinDifference) {
ans = S.substr (i, SZ_T);
MinDifference = CurrentDifference;
}
}
cout << ans << endl;
}
但是,我的方法仅在S
和T
的长度较短时才有效。 但是,问题是S
和T
的长度可以大到2 * 10^5
。 我该如何处理?
让我们最大化匹配的字符数。 我们可以对字母表中的每个字符分别求解,然后对子串的结果求和。 要解决特定字符的问题,请将字符串S
和T
作为序列 0 和 1 并使用 FFT https://en.wikipedia.org/wiki/Fast_Fourier_transform将它们相乘。
复杂度O(|A| * N log N)
其中|A|
字母的大小(大写字母为 26)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.