Title: Leetcode 014 Longest Common Prefix
Test instructions: Gives a set of strings for common prefixes
Idea: A lot of strings of public prefixes should not be very high, so direct violence to solve the good
However, there is a special sentence, that is, when there is only one string, you can return directly. In addition, it is important to note that each time you use the subscript to access the string, be sure to determine whether in the valid range .
The code is as follows:
1 classSolution {2 Public:3 stringLongestcommonprefix (vector<string>&STRs) {4 intn =strs.size ();5 if(n = =0)return "";6 stringstr = strs[0];7 for(inti =1; I < n; i++)8 {9 intLen1 = Str.size (), len2 =strs[i].size ();Ten if(Len1 = =0|| Len2 = =0)return ""; One intLen =0; A stringTMP =""; - while(Len < len1 && Len < len2 && Str[len] = =Strs[i][len]) -TMP + = str[len++]; thestr =tmp; - } - returnstr; - } +};
"Leetcode" 014 longest Common Prefix