Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "" .
Example:
input : [ "flower" , "flow" , "flight" ]
output : fl
input : [ "dog" , "racecar" , "car" ]
output : "" (empty string)
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class LongestCommonPrefix{ public static void main(String []args){ String[] arr = { "flower", "flow", "flight" }; String result = findLongestCommonPrefix(arr); System.out.print(result); } public static String findLongestCommonPrefix(String[] arr){ String lcp = ""; // longest common prefix int index = 0; if(arr==null || arr.length==0) return lcp; for(char c : arr[0].toCharArray()){ for(int i=1; i<arr.length; i++){ if( index >= arr[i].length() || c != arr[i].charAt(index) ) return lcp; } lcp += c ; index++; } return lcp; } } |
Python
def findLongestCommonPrefix(arr): lcp = "" # longest common prefix index = 0 if(arr == None or len(arr)==0): return lcp for c in arr[0]: for word in arr: if index > len(word) or c != word[index]: return lcp lcp += c index += 1 return lcp arr = [ "flower", "flow", "flight"] print(findLongestCommonPrefix(arr))