下面是我实施“最长公共子串”的蛮力方式
class Solution {
public:
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
int longestCommonSubstring(string &A, string &B) {
// write your code here
if (A.length() > B.length()) {
return longestCommonSubstring(B, A);
}
string str1, str2;
int maxlen = 0, len = A.length();
for (int i = 0; i < len; i++) { //1 * len
for (int j = 1; j <= len - i; j++) { //
str1 = A.substr(i, j);
for (int m = 0; m <= B.length() - j; m++) {
str2 = B.substr(m, j);
if (str1 == str2) {
maxlen = max(maxlen, j);
}
}
}
}
return maxlen;
}
}
然而,我坚持这个时间的复杂性,特别是对于第三个循环。我知道前两个循环应该是O(N ^ 2),N是A的大小。但是我不知道如何涉及第三个循环。有人能给我计算方法吗?非常感谢