LeetCode - Longest Common Prefix
2013.12.1 23:23
Write a function to find the longest common prefix string amongst an array of strings.
Solution:
For two string s1 and s2, compare the elements from the beginning, when the end or the first mismatch is found, the common prefix is found.
For n strings s[n], perform (n - 1) times such comparings. If the current common prefix is already empty "", then the latter comparison is meaningless and cancelled.
Time complexity is O(n * max(strlen(s[i]))), that means the comparison can be performed at most (n - 1) times, and no single comparison will go longer than the longest string amongst s[n]. Space complexity is O(1).
Actually, if we find out the shortest string s_min amongst s[n], and start the first comparison from the shortest string. We'll gain a time complexity of O(n * min(strlen(s[i]))). Space complexity remains O(1).
Here is an example to show why order of the data matters:
['aaa', ''aaa', 'aaa', 'd']
['d', 'aaa', 'aaa', 'aaa']
The time needed for the two dataset above would be different, since order is different. It's better to put short ones on the front.
Accepted code:
1 // 1RE, 1AC 2 #include <algorithm> 3 using namespace std; 4 5 class Solution { 6 public: 7 string longestCommonPrefix(vector<string> &strs) { 8 // IMPORTANT: Please reset any member data you declared, as 9 // the same Solution instance will be reused for each test case. 10 int n = strs.size(); 11 // 1RE here, didn't consider the case when $strs is empty. 12 if(n <= 0){ 13 return ""; 14 } 15 string res = strs[0]; 16 17 int i; 18 for(i = 1; i < n; ++i){ 19 res = commonPrefix(res, strs[i]); 20 if(res == ""){ 21 break; 22 } 23 } 24 25 return res; 26 } 27 private: 28 string commonPrefix(string s1, string s2) { 29 if(s1.length() > s2.length()){ 30 return commonPrefix(s2, s1); 31 } 32 33 int len1, len2; 34 35 len1 = s1.length(); 36 len2 = s2.length(); 37 int i; 38 for(i = 0; i < len1; ++i){ 39 if(s1[i] != s2[i]){ 40 break; 41 } 42 } 43 44 return s1.substr(0, i); 45 } 46 };