• 【LeetCode & 剑指offer刷题】字符串题10:Longest Common Prefix


    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

     Longest Common Prefix

    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.

    C++
     
    //问题:各字符串最长公共前缀
    /*
    class Solution
    {
    public:
        string longestCommonPrefix(vector<string>& strs)
        {
            if(strs.size() == 0) return ""; //返回空串
            if(strs.size() == 1) return strs[0]; //返回自身
           
            string res = strs[0]; //初始化
            int length = res.size(); //公共前缀的长度
            for(int i = 1; i<strs.size(); i++) //从第二个单词开始遍历
            {
                int temp = -1;
                for(int j = 0; j<length && j<strs[i].size(); j++)//遍历单词内字符
                {
                    if(strs[i][j] == res[j] ) temp  = j; //保存当前索引
                    else break; //一旦不相等就退出循环
                }
                length = temp + 1;
            }
            res[length] = ''; //打上结束字符
           
            return res;
        }
    };*/
    //也可用string的成员函数substr简化程序
    class Solution
    {
    public:
        string longestCommonPrefix(vector<string>& strs)
        {
            if(strs.empty()) return ""; //返回空串
           
            string prefix = strs[0];
            for(int i = 1; i<strs.size(); i++)
            {
                for(int j = 0; j<prefix.size(); j++)
                {
                    if(strs[i][j] != prefix[j])
                    {
                        prefix = prefix.substr(0, j); //公共前缀更新,substr中区间为前闭后开,故当遇到第一个不相等字符后,就将前面相等的字符复制过去,之后j<prefix.size()无法满足,退出循环。
                    }
                }
            }
           
           
            return prefix;
        }
    };
     
  • 相关阅读:
    nodejs事件和事件循环详解
    keycloak集群化的思考
    Python解释器和IPython
    IndexedDB详解
    在onelogin中使用OpenId Connect Implicit Flow
    在onelogin中使用OpenId Connect Authentication Flow
    SAML和OAuth2这两种SSO协议的区别
    wildfly 21的配置文件和资源管理
    【老孟Flutter】2021 年 Flutter 官方路线图
    【老孟Flutter】为什么 build 方法放在 State 中而不是在 StatefulWidget 中
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10224858.html
Copyright © 2020-2023  润新知