This is also a simple topic, but the key is test instructions understanding.
The title is in the sentence: Write a function to find the longest common prefix string amongst an array of strings.
Test instructions is a string array that finds the longest common prefix of all strings in this string array.
Note that it is a qualified prefix, not a substring.
So, the direct solution is to compare each character by the first string as a benchmark. The algorithm complexity is also obviously O (m*n), M is the number of strings, N is the longest prefix length.
The code is as follows:
classSolution { Public:stringLongestcommonprefix ( vector<string>&strs) {intLen = Strs.size ();stringPrefixif(len = =0)returnRes for(intpos =0; POS < strs[0].size (); pos++)//Longest prefix length does not exceed strs[0].size (), character-by-characters comparison{//character comparison of the corresponding position of each string for(intK =1; K < Len; k++) {if(strs[k].size () = = pos | | strs[k][pos]! = strs[0][pos])returnRes } prefix.push_back (strs[0][pos]); }returnPrefix }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode LCP (Longest Common Prefix) problem