Leetcode 14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
题目要求在字符串数组中找到最前面的公共子串。题目本身语义不清,引用diss中的解释(粗体部分)方便理解。
For example:
-
{"a","a","b"} should give "" as there is nothing common in all the 3 strings.
-
{"a", "a"} should give "a" as a is longest common prefix in all the strings.
-
{"abca", "abc"} as abc
-
{"ac", "ac", "a", "a"} as a.
最正常的思路是将数组中第一个字符串的字符与其他字符串的字符作比较,因此需要两重循环,第一重循环循环的是第一个字符串的字符,第二个循环循环的是数组中的字符串,当出现字符不匹配时返回当前的公共子串;若在数组中均可匹配则字符后移。
代码如下:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string pre = "";
if (strs.size() == 0)
return pre;
int min = INT_MAX;
for (auto &s:strs)
min = (s.length() < min) ? s.length() : min;
for (int i = 0; i < min; i++)
{
char temp = strs[0][i];
for (auto &s:strs)
{
if (s[i] != temp)
{
return pre;
}
}
pre += temp;
}
return pre;
}
};