Longest Common Prefix[easy]
Description
Write a function to find the longest common prefix string amongst an array of strings.
Solution
这道题是在给定的n个string中寻找最长前缀;
我们可以确定最长前缀的长度小于任意一个字符串的长度。
采取的思路是:先假定最长前缀为第一个string,然后通过匹配其它的string,不断改变最长前缀的长度。
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int s = strs.size();
if (s == 0) return "";
int l = strs[0].size();
for (int i = 0; i < s; i++) {
int j;
for (j = 0; j < min(l, (int)strs[i].size()); j++) {
if (strs[0][j] != strs[i][j]) break;
}
if (j < l) l = j;
}
return strs[0].substr(0, l);
}
};