This algorithm i wrote to check whether one string is a prefix for another string in the array. The complexity is O(n*(n-1)*k), where n is the number of strings in the array, and K is the largest length of the string. Am I right here in complexity analysis?
public static void isPrefix(String[] strs){
for(int i=0; i<strs.length; i++){
for(int j=i+1; j<strs.length; j++){
String a = strs[i];
String b = strs[j];
if(!commonStr(a,b).isEmpty()){
System.out.println(a + "->" + b);
}
}
}
}
private static String commonStr(String a, String b){
int smaller = Math.min(a.length(), b.length());
for(int k=0; k<smaller; k++){
if(a.charAt(k) != b.charAt(k)){
return "";
}
}
return a.substring(0,smaller);
}
public static void main(String[] args){
String[] strs = {"ab", "abc", "cde", "abef"};
isPrefix(strs);
}
You're right, I believe. It's just that K is not exactly that. But roughly speaking it's OK to say so.
Also it is K * n * (n-1) / 2
as you don't inspect all
ordered couples of strings (you inspect only half of them).
In your example, you inspect 6 couples, not 12.
Note that if your strings are say between 1 million and 2 million chars long,
but your n is just say 20 or 50 or 100, then K prevails and this estimate
is to be interpreted with care. Typically one would expect n >> K though,
I guess that's what you had in mind too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.