• Leetcode No.14 Longest Common Prefix最长公共前缀(c++实现)


    1. 题目

    1.1 英文题目

    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 "".

    1.2 中文题目

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

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

    1.3输入输出

    输入 输出
    strs = ["flower","flow","flight"] "fl"
    strs = ["dog","racecar","car"] ""

    1.4 约束条件

    • 1 <= strs.length <= 200
    • 0 <= strs[i].length <= 200
    • strs[i] consists of only lower-case English letters.

    2. 分析

    2.1 一般方法

    看到这道题,最简单的方法就是两层for循环,最外层是对第一个字符串进行遍历(其实第几个字符串都无所谓),内层是对字符数组进行遍历,意思也就是先看所有字符串第一个元素是否都一样,再看第二个,第三个,以此类推,当遇到有不同的时候,就可以跳出外层循环。代码如下:

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            string ans;
            for (unsigned int i = 0; i < strs[0].size(); i++)
            {
                unsigned int count = 0;
                for (unsigned int j = 0; j < strs.size(); j++)
                {
                    char temp = strs[0][i];
                    if (i != strs[j].size() && strs[j][i] == temp)//
                        count++;
                    else
                        goto here;
                    if (count == strs.size())
                        ans += strs[0][i];
                }
            }
        here:
            return ans;
        }
    };
    

    2.2 改进算法(贼好使)

    上述算法使用goto跳出两层循环,而goto的使用很多人是不太推荐使用的,同时联想到for循环的第二项就是一个判断语句,因此可以将goto判断语句改到for循环里,具体代码如下:

    class Solution {
    public:
        string longestCommonPrefix(vector<string>& strs) {
            string ans;
            for (unsigned int i = 0; i < strs[0].size(); i++)
            {
                unsigned int count = 1;
                unsigned int j = 1;
                int temp = strs[0][i];
                for (; j < strs.size() && i != strs[j].size() && strs[j][i] == temp; j++)
                    count++;
                if (count == strs.size())
                    ans += strs[0][i];
                else
                    break; 
            }
            return ans;
        }
    };
    

    这个算法时间消耗0ms,空间消耗9M,非常不错!

    作者:云梦士
    本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    div中嵌套div中使用margin-top失效问题
    thinkphp点击导航变色
    thinkphp I() 方法
    判断是手机端还是电脑端 isMobile()
    手机端H5 header定义样式
    AR.Drone 2.0四轴飞机体验:最好的玩具航拍器
    这是一个专注于电脑技术、软件应用、互联网、嵌入式,电子技术行业等的原创IT博客
    ul li列子
    [HTML]去除li前面的小黑点,和ul、LI部分属性
    Bad update sites
  • 原文地址:https://www.cnblogs.com/yunmeng-shi/p/15040005.html
Copyright © 2020-2023  润新知