在clasas中,我已經開始學習如何計算各種算法的運行時複雜度函數,並且發現它很困難。我正在嘗試計算下面遞歸算法的最壞情況下的運行時間複雜度。計算遞歸算法的最壞情況運行時間複雜度
目前我選擇我的基本操作是兩個字符的索引之間的比較,它發生在if語句中。然而這個if語句是嵌套的,我不確定這是如何影響遞歸算法中的t(n)的。
我認爲最壞的情況下運行時間複雜度是t(n) = N(N-1) = N^2 -1 or just O(n)=N^2?
我認爲在最壞的情況下,每個n個字符都會在外部if語句中檢查,這意味着n在內部if語句中將會比較-1個字符。
public class StringShuffleTest {
public static boolean isOrderedShuffle(String a, String b, String c){
//variables for the size of Strings a, b and c.
int n = a.length();
int m = b.length();
int len = c.length();
//if the length of c is not the length of a + b, return false.
if (len != (n + m)){
return false;
}
//if String c contains String b as a substring, then remove String b from c and make m = 0.
//This statement avoids errors when dealing with Strings with very similar characters.
if (c.contains(b)){
c = c.replace(b, "");
m = 0;
}
//if the length of a or b is 0, and c equals a or b, return true, otherwise,
//return false.
if (n == 0 || m == 0){
if (c.equals(a) || c.equals(b)){
return true;
}
else
return false;
}
//if String a has length 1, remove a from String c and make String a empty.
if (n == 1){
c = c.substring(0, c.indexOf(a.charAt(0))) + c.substring(c.indexOf(a.charAt(0)) +1);
a = "";
return isOrderedShuffle(a, b, c);
}
//An ordered shuffle of two given strings, a and b, is a string that can be formed by interspersing
//the characters of a and b in a way that maintains the left-to-right order of the characters from each
//string.
//Recursive algorithm to determine if String c is an ordered shuffle of a and b.
else
if (c.indexOf(a.charAt(0)) >= 0){
int indexOfFirsta = c.indexOf(a.charAt(0));
int indexOfSeconda = c.indexOf(a.charAt(1));
if (indexOfFirsta <= indexOfSeconda){
c = c.substring(0, indexOfFirsta) + c.substring(indexOfFirsta +1);
a = a.substring(1, n);
System.out.println(a);
System.out.println(c);
return isOrderedShuffle(a, b, c);
}
else
if (c.indexOf(b.charAt(0)) >= 0){
int indexOfFirstb = c.indexOf(b.charAt(0));
int indexOfSecondb = c.indexOf(b.charAt(1));
if (indexOfFirstb <= indexOfSecondb){
c = c.substring(0, indexOfFirstb) + c.substring(indexOfFirstb +1);
b = b.substring(1, m);
System.out.println(b);
System.out.println(c);
return isOrderedShuffle(a, b, c);
}
}
}
return false;
}
public static void main(String[] args) {
System.out.println(StringShuffleTest.isOrderedShuffle("abc", "def", "abedcf"));
}
}