最长公共前缀
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnmav1/
来源:力扣(LeetCode)
题目描述:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串
""
。
示例 :
输入: ["flower","flow","flight"] 输出: "fl"
答案v1.0
class Solution
{
public:
string longestCommonPrefix(vector<string> &strs)
{
string temp;
int cnt = 0;
if (strs.size() == 1)
{
return strs[0];
}
if (strs.size() == 0)
{
return "";
}
for (int j = 0; j < strs[0].size(); j++)
{
cnt = 0;
for (int i = 1; i < strs.size(); i++)
{
if (j < strs[i].size())
{
if (strs[0][j] == strs[i][j])
{
cnt++;
}
else
{
break;
}
}
else
{
break;
}
}
if (cnt == strs.size() - 1) //判断首字母重复次数和数组个数一样
{
temp += strs[0][j];
}
else
{
break;
}
}
return temp;
}
};