Topic:
Write a function to find the longest common prefix string amongst an array of strings.
Code:
classSolution { Public: stringLongestcommonprefix (vector<string>&STRs) { if(strs.size () = =0)return ""; STD::stringTmp_str = strs[0]; for(size_t i =1; I < strs.size (); ++i) {size_t J=0; for(; J < Std::min (Tmp_str.size (), strs[i].size ()); + +j)if(Tmp_str[j]!=strs[i][j]) Break; Tmp_str= Tmp_str.substr (0, J); } returnTmp_str; }};
Tips
Space complexity O (N1), Time complexity O (n1+n2 ...)
Each string string in the STRs is compared sequentially by 22, preserving the common prefix for this comparison to Tmp_str; the next time you compare it, you can use the last common prefix as the target string.
The benefit of this solution is that the code is relatively consice, but the spatial complexity and time complexity are not optimal.
"Longest Common Prefix" cpp