Write a function to find the longest common prefix string amongst an array of strings.
Solution: A comparison of all strings from the head to the end of each letter.
classSolution { Public: stringLongestcommonprefix (vector<string>&STRs) { intn = strs.size (), i =0; BOOLFlag =false; if(n = =0)return string(""); if(n = =1)returnstrs[0]; while(true) { for(intj =0; J < N-1; J + +) { if(I >= strs[j].size () | | strs[j][i]! = strs[j +1][i]) {flag=true; Break; } } if(flag) Break; I++; } return string(strs[0].begin (), strs[0].begin () +i); }};
Streamline to get a more concise version of the code:
classSolution { Public: stringLongestcommonprefix (vector<string>&STRs) { intn =strs.size (); if(n = =0)return string(""); for(inti =0; I < strs[0].size (); i++) { for(intj =0; J < N-1; J + +) { if(I >= strs[j].size () | | strs[j][i]! = strs[j +1][i])returnSTRS[J].SUBSTR (0, i); } } returnstrs[0]; }};
[Leetcode]32. Longest Common prefix the longest common prefix