题目:
Write a function to find the longest common prefix string amongst an array of strings.
思路:
也是easy级别的题目。对这种难度的题目来说,优秀的程序员的功底就体现在如何把代码写的简洁优雅(自己原来写的代码将近30行,太low了)。
代码:
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size() == 0)
return "";
string prefix;
for(int i = 0; i < strs[0].size(); i++)
{
char c = strs[0][i];
for(auto ch: strs)
{
// ch might not have the same length
if(i == ch.size() || ch[i] != c)
return prefix;
}
prefix += c;
}
return prefix;
}
};