zoukankan      html  css  js  c++  java
  • 力扣--最长公共前缀

    最长公共前缀

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

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

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

    示例 1:

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

    示例 2:

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

    提示:

    • 0 <= strs.length <= 200
    • 0 <= strs[i].length <= 200
    • strs[i] 仅由小写英文字母组成

    代码

    /*
     * @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
    
    
  • 相关阅读:
    MySQL-多条件拼接语句
    MongoDB-C#驱动基本操作
    MongoDB-C#驱动帮助
    MongoDB-权限配置
    MongoDB-安装
    C#_实用
    提高C#代码质量-规范
    C#_Express-ickd接口
    Eclipse背景颜色修改
    Java中可变长参数的方法
  • 原文地址:https://www.cnblogs.com/printwangzhe/p/14529657.html
Copyright © 2011-2022 走看看