Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

求字符串数组中字符串的最长公共前缀。

Solutions

  • 1 Longest Common Prefix -- 11~13ms

    • 第一个映入大脑的是对每一个字符串,按字符位逐个比较,直到发现不相同的或者是有个字符串已经比较完了时,说明最大公共前缀已经找到。则时间复杂度是: \(O(MN)\) 其中 M 是字符数组的个数,N 是字符数组中最短字符串的长度。按这种思想的代码如下:
    class Solution {
    public:
    string longestCommonPrefix(vector<string> &strs) {
    if(strs.size()<=0)return string();
    int idx=0;
    string res;
    char c;
    string s=strs.at(0); //以第一个字串作为比较的基
    int n=s.size(),ns=strs.size();
    while(idx<n){
    c=strs.at(0).at(idx); //获取一个字符
    for(int i=0;i<ns;++i){ //循环和其他字串中对应位的字符进行比较
    s=strs.at(i);
    if(idx<s.size())
    if(s.at(idx)==c)continue;
    idx=n; //如果出现不相等或有字符串已结束,则退出循环
    break;
    }
    if(idx<n){
    res.push_back(c);
    }
    ++idx;
    }
    return res;
    }
    };
    • 分析了一下,这里占用时间的有两个:

      1. 每一次迭代时的字符串拷贝;
      2. 如果最短的字符串在最后一个比较或靠后比较,则就白白浪费了太多比较了,特别是字符串数组很大的时候。
    • 所以对方案 1 进行了改进,有了下面的方案 2 。
  • 2 Longest Common Prefix -- 8ms

    • 这种方案首先找到字串数组中最短的那个,并记录下其在字符数组中的下标,不进行拷贝,减少空间复杂度,同时,节省一点时间。
    • 其次,去除掉所有的字符串拷贝操作,除用于在大字符串数组情况下的优化时需要的变量外,尽量减少空间使用。可以看到,运行时间一下子减到了 8ms。说明还是有效果的。
    • 代码如下:
    class Solution {
    public:
    string longestCommonPrefix(vector<string> &strs) {
    if(strs.size()<=0)return string();
    int idx=0,base=0;
    string res;
    int ns=strs.size();
    while(idx<ns){
    if(strs.at(idx).size()<strs.at(base).size())
    base=idx;
    ++idx;
    }
    idx=0;
    char c;
    int n=strs.at(base).size();
    while(idx<n){
    c=strs.at(base).at(idx);
    for(int i=0;i<ns;++i){
    if(idx<strs.at(i).size())
    if(strs.at(i).at(idx)==c)continue;
    idx=n;
    break;
    }
    if(idx<n){
    res.push_back(c);
    }
    ++idx;
    }
    return res;
    }
    };
  • 3 Longest Common Prefix -- 8ms

    • 查阅了网友的解答,发现这样一种思路:
    • 以第一个字串为比较基的长度判定,逐位判断,如果发现有一个字串的长度小于或等于当前位,说明这个字串结束了,自然也应该结束函数;
    • 如果没有结束,逐位判断的方式使用:判断当前字串的当前位和下一个字串的当前位比较是否相同,不相同则结束。可以看到,效率还是很高的。
    class Solution {
    public:
    string longestCommonPrefix(vector<string> &strs) {
    if (strs.size() == 0) return "";
    string s;
    for (int i = 0; i < strs[0].length(); i++) {
    for (int j = 0; j < strs.size() - 1; j++) {
    if (strs[j + 1].length() <= i || strs[j][i] != strs[j + 1][i]) {
    return s;
    }
    }
    s.push_back(strs[0][i]);
    }
    return s;
    }
    };
    • 代码看起来很简洁,但我认为,代码还应该有改进方式,比如应该先遍历出最短的那个字串,同时,求strs.size()尽量放到循环外面来,因为其是一个常量,在内层循环中,如果字串数组很大,就会产生一定的无法消除的效率影响。同时,我更喜欢使用 ++i 代替 i++ ,因为这样,能减少一次寄存器存取。也许当数据量少时看不出来这些差距,但代码在手,能优尽优嘛!不过处理了这些,好像就没原来的好看了~~

      LeetCodeOJ刷题之14【Longest Common Prefix】的更多相关文章

      1. 【leetcode刷题笔记】Longest Common Prefix

        Write a function to find the longest common prefix string amongst an array of strings. 题解:以strs[0]为模 ...

      2. leetCode练题——14. Longest Common Prefix

        1.题目 14. Longest Common Prefix   Write a function to find the longest common prefix string amongst a ...

      3. 14. Longest Common Prefix【leetcode】

        14. Longest Common Prefix Write a function to find the longest common prefix string amongst an array ...

      4. [LeetCode][Python]14: Longest Common Prefix

        # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'https://oj.leetcode.com/problems/longest ...

      5. Leetcode 14. Longest Common Prefix(水)

        14. Longest Common Prefix Easy Write a function to find the longest common prefix string amongst an ...

      6. LeetCode第[14]题(Java): Longest Common Prefix

        题目:最长公共前缀 难度:EASY 题目内容: Write a function to find the longest common prefix string amongst an array o ...

      7. Java [leetcode 14] Longest Common Prefix

        小二好久没有更新博客了,真是罪过,最近在看linux的东西导致进度耽搁了,所以今晚睡觉前怒刷一题! 问题描述: Write a function to find the longest common ...

      8. 14. Longest Common Prefix 最长的公共字符串开头

        [抄题]: Write a function to find the longest common prefix string amongst an array of strings. 在 " ...

      9. 14. Longest Common Prefix

        题目: Write a function to find the longest common prefix string amongst an array of strings. Subscribe ...

      随机推荐

      1. vim(三)golang代码跳转配

        在golang的代码里跳来跳去.... godef 安装 跳转是通过godef实现,godef的安装目录一般是$GOBIN,只要让godef命令在$PATH下即可 godef 命令安装: go get ...

      2. centos 7 查看系统版本信息

        2018-11-06 1. 查看版本号  CentOS的版本号信息一般存放在配置文件当中,在CentOS中,与其版本相关的配置文件中都有centos关键字,该文件一般存放在/etc/目录下,所以说我们 ...

      3. app测试中,ios和android的区别

        App测试中ios和Android的区别: 1. Android长按home键呼出应用列表和切换应用,然后右滑则终止应用: 2. 多分辨率测试,Android端20多种,ios较少: 3. 手机操作系 ...

      4. string查找字符(串)

        在C语言中 strchr 和 strstr函数都被包含在<string.h>头文件中,也就是要调用它们时要在程序前面包含<string.h>头文件,也就是写这个语句:#incl ...

      5. AWS and OpenStack

        AWS OpenStack EC2 Nova EBS Cinder EFS Manila S3 Swift Storage Gateway 本地上云 ClondFront 内容发布服务 VPC Neu ...

      6. filter 静态资源

        package com.itheima.web.filter; import java.io.IOException; import javax.servlet.Filter; import java ...

      7. 016-hibernateutils模板

        package ${enclosing_package}; import org.hibernate.HibernateException; import org.hibernate.Session; ...

      8. git读书笔记以及使用技巧

        [添加文件] git add  把文件修改添加到暂存区    git commit -m '' 把暂存区的所有内容提交到当前分支 [查看历史]    git log 查看提交历史 git log -- ...

      9. PHP中break及continue两个流程控制指令解析

        <?php $arr = array( 'a' => '0a0', 'b' => '0b0', 'c' => '0c0', 'd' => '0d0', 'e' => ...

      10. this,super,和继承

        this是指当前对象的引用,super是指直接父类的引用 比如 我建造一个类 public class Person(){ private String name; private  int age; ...