其他分享
首页 > 其他分享> > 力扣--最长公共前缀

力扣--最长公共前缀

作者:互联网

最长公共前缀

Category Difficulty Likes Dislikes
algorithms Easy (39.25%) 1495 -

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例 1:

输入:strs = ["flower","flow","flight"]
输出:"fl"

示例 2:

输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。

提示:


代码

/*
 * @lc app=leetcode.cn id=14 lang=cpp
 *
 * [14] 最长公共前缀
 */

// @lc code=start
class Solution
{
public:
    string longestCommonPrefix(vector<string> &strs)
    {
        //公共前缀
        string str, temple;
        //重合次数 n=0;
        int n = 0;
        //防止数据为[] 
        if (!strs.size())
            return "";
        //赋初值 不赋""的原因是防止输入["a"],返回值为""
        str = strs[0];
        temple = strs[0];

        for (int i = 0; i < strs.size(); i++)
        {
            //如果AB的公共前缀大于BC的公共前缀 取BC公共前缀
            if (str.length() > temple.length())
            {
                
                str = temple;                
                if (str == "")
                    break;
            }

            if (i + 1 < strs.size())
            {
                //初始化
                temple = "";
                for (int j = 0; j < min(strs[i].length(), strs[i + 1].length()); j++)
                {
                
                    if (strs[i].at(j) == strs[i + 1].at(j))
                    {
                        temple += strs[i].at(j);
                    }
                    else
                    {
                        break;
                    }
                
                }
            }
        }
        return str;
    }
    
};
// @lc code=end

标签:前缀,--,力扣,strs,length,str,公共,temple
来源: https://www.cnblogs.com/printwangzhe/p/14529657.html