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 "".
This is a solution from leetcode:
Approach 1: horizontal scanning
publicclassLongestCommonPrefix{publicstaticStringlongestCommonPrefix(String[]strs){// if the length of the string array is zero, return "";if(strs.length==0){return"";}// Name the first element in string array as prefix;Stringprefix=strs[0];//Loop from the second element in "strs" to the last onefor(inti=1;i<strs.length;i++){// If the current element contains the prefix, move to the// next element and do the comparison again with the prefixwhile(strs[i].indexOf(prefix)!=0){// Chop down the tail character of prefixprefix=prefix.substring(0,prefix.length()-1);// Return "" when prefix is emplyif(prefix.isEmpty()){return"";}}}returnprefix;}// Testpublicstaticvoidmain(String[]args){// Array of stringsString[]res={"English","Engli","EnE"};Stringresult=longestCommonPrefix(res);// Show resultSystem.out.println(result);}}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)