计算算法

时间:2015-12-02 23:04:40

标签: java algorithm big-o time-complexity

我试图找出我创建的算法的最坏情况运行时复杂度,该算法检查给定的String是否是字符串列表的封面字符串(对于列表中的每个字符串,包含其中的每个字符串字符)它,保持从左到右的顺序)。

我目前认为此算法的最坏情况运行时复杂度是否为O(N ^ 2),我是否正确?我的逻辑是,对于执行n次的内部for循环,调用复杂度为O(1)的if语句。并且外循环也执行n次,导致n * n或O(n ^ 2)的t(n)。

public class StringProcessing {

//ArrayList created and 3 fields added.
public static ArrayList<String> stringList = new ArrayList<>();
public static String list1 = "abc";
public static String list2 = "def";  
//public static String list3 = "fad"; 
//public static String list4 = "monkey";
//public static String list5 = "def";

//Boolean method to test whether a given string is a cover string for a single string.
//Method contains a for-each loop to iterate through characters of test String s.
public static boolean isSingleCover(String s, String cover)
{      
    int i = 0;
    for(char c : s.toCharArray())
        if((i = cover.indexOf(c, i)) == -1)
            return false;
    return true;
}

//Second Boolean method to test whether a given string is a cover string for a given list of strings.
//The algorithm includes reference to the previous method for testing a single String, and uses this method
//for each string in the ArrayList.
public static boolean isCover(ArrayList<String> list, String cover)
{
    stringList.add(list1);
    stringList.add(list2);
    //stringList.add(list3);
    //stringList.add(list4);
    //stringList.add(list5);
    for(String s : list)
        if(!isSingleCover(s, cover))
            return false;
    return true;
}

public static void main(String[] args) {
    System.out.println(StringProcessing4.isCover(stringList, "adftyhgusbgusibadsjfksvgjchjgdkepf"));
}

}

1 个答案:

答案 0 :(得分:1)

Java的implementation indexOf的复杂性是O(m * n),其中n和m分别是搜索字符串和模式的长度。

最坏情况复杂度O(N * M * C),当N = stringList.size()时,M = stringList.get(...)。length()和C = cover.length()