Write a function to find the longest common prefix string amongst an array of strings.
解法:从所有的string的头到尾的字母逐一比较即可。
class Solution { public: string longestCommonPrefix(vector<string>& strs) { int n = strs.size(), i = 0; bool flag = false; if (n == 0) return string(""); if (n == 1) return strs[0]; while (true) { for (int j = 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); } };
精简得到一个更简洁的代码版本:
class Solution { public: string longestCommonPrefix(vector<string>& strs) { int n = strs.size(); if (n == 0) return string(""); for(int i = 0; i < strs[0].size(); i++) { for (int j = 0; j < n - 1; j++) { if (i >= strs[j].size() || strs[j][i] != strs[j + 1][i]) return strs[j].substr(0, i); } } return strs[0]; } };