Showing posts with label String Matchin. Show all posts
Showing posts with label String Matchin. Show all posts

Wednesday, August 24, 2011

Write a function to find the longest common prefix string amongst an array of strings



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)