Problem:Write a function to find the longest common prefix string amongst an array of strings.
Solution:time complexity O (n)
Main topic:give a string array to find the maximum prefix common substring of these strings. Problem Solving Ideas:since it is a common substring, that each string must contain, and in the head, first the first string as the default maximum, and then followed by each string in contrast, calculate all the maximum matching length, the smallest is the length
Java source code (spents 263ms):when it comes to string processing, Java consumes much more time than other languages.
public class Solution {public String longestcommonprefix (string[] strs) { if (strs.length==0) return ""; Char[] Str=strs[0].tochararray (); int min=str.length; for (int i=1;i<strs.length;i++) { char[] S=strs[i].tochararray (); int j=0; while (j<min && j<s.length && s[j]==str[j]) j + +; Min = min>j?j:min; } Return strs[0].substring (0,min);} }
C Language Source code (spents 6ms):
char* Longestcommonprefix (char** strs, int strssize) { char* str=strs[0]; int i,j; if (strssize==0) return ""; for (i=1;i<strssize;i++) { j=0; while (Str[j] && strs[i][j] && Str[j]==strs[i][j]) j + +; str[j]=0; } return str;}
C + + source code (spents 8ms):
Class Solution {public: string Longestcommonprefix (vector<string>& STRs) { if (strs.size () ==0) Return ""; char* str= (char*) malloc (sizeof (char) * (Strs[0].size () +1)); for (int i=0;i<strs[0].size (); i++) { str[i]=strs[0][i]; } Str[strs[0].size ()]=0; for (int i=1;i<strs.size (); i++) { int j=0; while (Str[j] && strs[i][j] && Str[j]==strs[i][j]) j + +; str[j]=0; } return string (str);} ;
python source code (spents 66ms):
Class solution: # @param {string[]} strs # @return {string} def longestcommonprefix (self, STRs): If Len (STRs) ==0:return "" Str=strs[0] min=len (str) for I in range (1,len (STRs)): J=0;p=strs[i] While j <min and J<len (p) and p[j]==str[j]:j+=1 min = min If min<j else J return Str[:min]
Leetcode longest Common Prefix (C,c++,java,python)