Simple Algorithm Will Go Like This:
Algorithm:Longest Common Prefix ( LCP)
1.Take a String From Array Whose length is Minimum else
you might get exception if tries to access array element
outside range.why this will work because if there exist
a common prefix then it will be the desired answer .
Example like in case of "shash" ,"shank","shashank" LCP will be "sha"
for this string "ab", "abc", "def" ,"defgh", "sha" LCP will be NULL
2.Keep Comparing reamining string character by character with 1st selected string if mismatch occurs at any position i then append 1st string to output string.
Working Code
String findLongPrefix(String [] str)
{
StringBuilder strBuilder = new StringBuilder();
char [] firstStr = str[0].toCharArray();
for(int i=0; i< str[0].length(); i++ ) {
boolean found = true;
for(String str: str) {
if(str.charAt(i) != firstStr[i]) {
found = false;
break;
}
}
if(found) {
strBuilder.append(firstStr[i]);
} else
break;
}
return strBuilder.toString();
}
Time Complexity O(N*M-1)=O( Where N is Length of 1st Smallest String
and M is Number of remaining string in string array so it will run
upto length of array-1
Space Complexity O(1)
2 comments :
You can do it in O(m*log(n)) where m is length or largest string and n is number of string.
Calculate prefix of 1st and last string and store it, then same for 2nd and 2nd last and so on. so you will do n/2 prefix computations and problem size will be reduced to half. Now apply same procedure on these n/2 until you get one. and that one string will be longest common prefix.
common(prefix(A),prefix(B),prefix(C),prefix(D)) = common(common(prefix(A),prefix(B)),common(prefix(C),prefix(D)));
@Guarav Approach Seems to Fine, Just Confused With TC shouldn't be O(nlogn), well can u tell me why uchoose m logn ??
Shashank
Post a Comment