Topic:
Write a function to find the longest common prefix string amongst an array of strings.
Test instructions
Write a function that finds the longest common substring in a set of arrays.
Algorithm Analysis:
You need to build a double loop. The first layer is the length of the shortest substring, and the other layer iterates through each member of the string array.
Brute force idea, with the first string as the standard, for each string starting from the first character, to see if it is consistent with the standard, if different, then jump out of the loop to return the current result, or continue the next character.
AC Code:
Public String Longestcommonprefix (string[] strs) { if (STRs = = NULL | | strs.length = 0) return ""; int minlen=integer.max_value; for (String str:strs) { if (Minlen > Str.length ()) Minlen = Str.length ();//Find the shortest substring in these strings } if ( Minlen = = 0) return ""; for (int j=0; j<minlen; j + +) { char prev= ' 0 '; for (int i=0; i<strs.length; i++) { if (i==0) { prev = Strs[i].charat (j);//The first character of a string is only tested at a time continue; } if (Strs[i].charat (j)! = prev)//If all strings are equal, remove a character and, if not equal, return the public prefix {return strs[i] that precedes the character . SUBSTRING (0, j); }} Return strs[0].substring (0,minlen);//All strings are prefixed equal to the shortest string length }
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Longest Common Prefix