Time complexity 真的不';我不知道如何计算下面代码的时间复杂度
下面是我实现“最长公共子字符串”的暴力方式Time complexity 真的不';我不知道如何计算下面代码的时间复杂度,time-complexity,Time Complexity,下面是我实现“最长公共子字符串”的暴力方式 类解决方案{ 公众: /** *@param A,B:两个字符串。 *@return:最长公共子串的长度。 */ int longestCommonSubstring(字符串A、字符串B){ //在这里编写代码 如果(A.length()>B.length()){ 返回最长的公共子串(B,A); } 字符串str1,str2; int maxlen=0,len=A.length(); 对于(int i=0;i
类解决方案{
公众:
/**
*@param A,B:两个字符串。
*@return:最长公共子串的长度。
*/
int longestCommonSubstring(字符串A、字符串B){
//在这里编写代码
如果(A.length()>B.length()){
返回最长的公共子串(B,A);
}
字符串str1,str2;
int maxlen=0,len=A.length();
对于(int i=0;i 对于(int j=1;j是被认为是常数的B
的大小,或者它的大小也是问题大小的一部分?如果是前者,它很容易;如果是后者,那么问题大小(N)不能只是A的长度。从最坏的情况开始:如果删除最内层循环中的-j
,会怎么样?这将是复杂性的上限。
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;
}