zoukankan      html  css  js  c++  java
  • 78 最长公共前缀

    原题网址:https://www.lintcode.com/problem/longest-common-prefix/description

    描述

    给k个字符串,求出他们的最长公共前缀(LCP)

    您在真实的面试中是否遇到过这个题?  

    样例

    在 "ABCD" "ABEF" 和 "ACEF" 中,  LCP 为 "A"

    在 "ABCDEFG", "ABCEFG", "ABCEFA" 中, LCP 为 "ABC"

    标签
    枚举法
    基本实现
    字符串处理
    LintCode 版权所有
     
    思路:这道题比较简单,首先找出字符串数组中长度最小的字符串,记录其长度。然后指针从0开始一直到最小长度,遍历所有字符串,逐个对比它们在当前指针下的字符是否相等,不相等 return 结果;相等则把当前字符添加到结果中。
     
    AC代码:
    class Solution {
    public:
        /**
         * @param strs: A list of strings
         * @return: The longest common prefix
         */
        string longestCommonPrefix(vector<string> &strs) {
            // write your code here
        string result="";
        int n=strs.size();
        if (n==0)
        {
            return result;
        }
        int minl=INT_MAX;
        for (int i=0;i<n;i++)//找到字符串中长度最小值;
        {
            if (strs[i].size()<minl)
            {
                minl=strs[i].size();
            }
        }
        if (minl==0)
        {
            return result;
        }
        int ind=0;
        while(ind<minl)//在长度最小值内搜索公共前缀;
        {
            char tmp=strs[0][ind];
            for (int i=1;i<n;i++)
            {
                if (strs[i][ind]!=tmp)
                {
                    return result;
                }
            }
            result+=tmp;
            ind++;
        }
        return result;
        }
    };

     

    其他方法:

    LintCode-最长公共前缀  直接两两对比,将第一个字符串作为参照,找出它与剩下字符串的最长公共前缀。

    LintCode 最长公共前缀  以第一个字符串为参照,固定列,逐行对比,找出最大前缀。

    https://www.jianshu.com/p/256c7a784283 方法同第二个链接,但代码更简洁

    lintcode-78-最长公共前缀

     

  • 相关阅读:
    Mybatis学习笔记14
    Mybatis学习笔记13
    Mybatis学习笔记12
    poj 2513
    poj 2001
    poj 1080
    poj 1703
    poj 1521
    poj 1384
    poj 1726
  • 原文地址:https://www.cnblogs.com/Tang-tangt/p/9302355.html
Copyright © 2011-2022 走看看