I. Title Description
Write a function to find the longest common prefix string amongst an array of strings.
Two. Topic analysis
The main idea of the topic is that given a set of strings, find the longest common prefix for all strings.
Comparing the longest common prefix of two strings, the length of the prefix must not exceed the shorter length of the two string, and the shortest string length is n , so long as the first character of the two strings is compared n .
Use a variable to prefix hold the longest public prefix of two strings, and then prefix compare the next string in the array as a new string, and so on.
In a special case, an empty string is returned directly if one of the string lengths in the array is 0 , or if the length of the current longest public prefix is evaluated 0 .
Three. Sample code
#include <iostream>#include <string>#include <vector>using namespace STD;classSolution { Public:stringLongestcommonprefix ( vector<string>&strs) {if(strs.size () = =0)return "";stringprefix = strs[0]; for(inti =1; I < strs.size (); ++i) {if(prefix.length () = =0|| Strs[i].length () = =0)return "";intLen = Prefix.length () < Strs[i].length ()? Prefix.length (): Strs[i].length ();intJ for(j =0; J < Len; ++J) {if(Prefix[j]! = Strs[i][j]) Break; } prefix = Prefix.substr (0, j); }returnPrefix }};
Four. Summary
The idea of the problem is not difficult, and there are several similar solutions, in the implementation of the need to minimize the number of comparison characters operation.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode notes: Longest Common Prefix