版权声明:转载需转载声明 https://blog.csdn.net/qq_32285693/article/details/84073923
Longest Common Prefix
Description:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z
.
解析:
例如:字符串
"f l ower"
"f l ow"
"f l ight"
每一次进行纵向比较,作为内循环 ,外循环为字符串的最小长度
string longestCommonPrefix(vector<string>& strs)
{
string result = "";
if(strs.size()<=0) // 判断字符串的个数是否小于0
{
return "";
}
int minLen = strs.at(0).size(); // 为最小字符串的长度赋值为第一个字符串的长度
for(int i =0;i<strs.size();i++) // 求取最小的字符串长度
{
if(minLen > strs.at(i).size())
{
minLen = strs.at(i).size();
}
}
if(minLen == 0) // 如果字符串中其中一个为空 则返回空
{
return "";
}
int j = 0,k = 0;
while(j < minLen)
{
while(k<strs.size()-1)
{
if(strs.at(k).at(j) == strs.at(k+1).at(j)) // 判断前缀字符是否相等
{
k++;
continue;
}
else // 任意出现不等的问题,则退出
{
k = strs.size()-1; // 退出内循环
j = minLen; // 退出外循环
}
}
if(j != minLen) // 表示前n个字符相等,并且j不等于最小字符串长度
{
result += strs.at(0).at(j); // 将字符串前几个字符相等的赋值给result
j++; // 外循环++
k = 0; // 内循环重新开始
}
}
return result;
}