Write a function to find the longest common prefix string amongst an array of strings.
本题寻找一组字符串的公共前缀,只需要查询较短子串前n个字符是否相等。时间:8ms
代码如下:
class Solution { public: string longestCommonPrefix(vector<string>& strs) { if (strs.size() == 0) return ""; string str = strs[0]; for (int i = 1; i < strs.size(); i++){ if (strs[i].size() == 0 || str.size() == 0) return ""; int n = (str.size()<strs[i].size() ?str.size():strs[i].size()); int j = 0; for (; j < n; j++){ if (str[j] != strs[i][j]) break; }; str = str.substr(0, j); } return str; } };