Title: Write a function to find the longest common prefix string amongst an array of strings.Main topic:write a function that asks for the longest common prefix substring in a string array. Ideas: before you do this question, you need to know what is called a public prefix substring. In English, a word can be divided into prefix, root, suffix three parts, so-called prefix refers to the word at the beginning of one or several characters. Accordingly, the string prefix substring refers to the string from the first character of one or several characters, such as: ABCdef and ABCEDF the longest common prefix substring is ABC, and ABCDEF and bbcdef the longest common prefix substring is an empty string, must not be assumed to be BCD. Specific ideas are as follows:1, if empty, returns an empty string directly2. Find the minimum length string in the array to prevent cross-border3, the minimum length of the string as an outer loop (because the longest public prefix is not longer than the minimum length of the string), every time to check whether all the strings are equal, if there is a inequality there is no need to check again, directly return the result string, if all is equal, the scanned word multibyte on the result string. Code:
Class Solution {public: std::string longestcommonprefix (std::vector<std::string>& strs) { //if blank, Returns the empty string directly if (strs.size () = = 0) { return ""; } std::string result = ""; Find the minimum length string to prevent crossing auto minSize = Strs[0].size (); for (auto &a:strs) { if (a.size () < minSize) { minSize = A.size (); } } The string with the minimum length is outer loop (because the longest public prefix will not be longer than the minimum length of the string) //Every time the string is checked for equality for (int i = 0; i < minSize; ++i) {for (int j = 0; J + 1 < strs.size (); ++J) { if (strs[j][i]! = strs[j + 1][i]) {//If there is an inequality there is no need to check it again to return result;} Result + = Strs[0][i]; If all are equal then the scanned word multibyte on the result string } return result;} ;
Leetcode---longest Common Prefix