【leetcode】Longest Common Prefix (easy)

时间:2021-03-25 07:46:12

Write a function to find the longest common prefix string amongst an array of strings.

思路:找最长公共前缀 常规方法

string longestCommonPrefix(vector<string> &strs) {
if(strs.size() == ) return "";
if(strs.size() == ) return strs[];
string ans;
int n = ;
while()
{
for(int i = ; i < strs.size(); i++)
{
if(strs[i].size() <= n || strs[i - ].size() <= n || strs[i][n] != strs[i - ][n]) //如果n超出了字符串长度 或对应位置不等 返回答案
{
return ans;
}
}
ans += strs[].substr(n, );
n++;
}
}