Write a function to find the longest common prefix string amongst an array of strings.
思路:每个字符串都与第0个字符串比较,设置一个变量,记录每个字符串与第0个字符串不匹配位置的最小值
时间复杂度O(n1+n2+...),空间复杂度O(0)
1 class Solution { 2 public: 3 string longestCommonPrefix(vector<string> &strs) { 4 if (strs.empty()) return ""; 5 6 int length = strs[0].size() - 1; 7 for (int i = 1; i < strs.size(); ++i) { 8 for (int j = 0; j <= length; ++j) { 9 if (strs[0][j] != strs[i][j]) 10 length = j - 1; 11 } 12 } 13 14 return strs[0].substr(0,length + 1); 15 16 } 17 };