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);}}
Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.
Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.
Top comments (0)