14.Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
Example 1:
1 2
| Input: strs = ["flower","flow","flight"] Output: "fl"
|
Example 2:
1 2 3
| Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
|
个人解答:
时间复杂度:O(n^2)
空间复杂度:O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| string longestCommonPrefix(vector<string>& strs) { string ans_string = ""; int nums_string = size(strs); int min_lenth_string = strs[0].length(); for (int i = 1; i < nums_string; ++i) { if (strs[i].length() < min_lenth_string)min_lenth_string = strs[i].length(); } for (int i = 0; i < min_lenth_string; ++i) { for (int j = 0; j < nums_string; ++j) { if (strs[0][i] != strs[j][i])return ans_string; } ans_string += strs[0][i]; } return ans_string; }
|
1 2 3 4 5 6 7 8 9 10 11
| string longestCommonPerfix(vector<string> strs) { sort(begin(strs), end(strs)); int size = strs.size(); int length = min(strs[0].size(), strs[size-1].size()); int index = 0; while (index < length) { if (strs[0][index] == strs[size-1][index]) ++index; else break; } return strs[0].substr(0, index); }
|