码迷,mamicode.com
首页 > 其他好文 > 详细

78 最长公共前缀

时间:2018-07-13 00:00:42      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:ant   common   get   https   longest   ble   pre   描述   def   

原题网址: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;
    }
};

 

 

 

78 最长公共前缀

标签:ant   common   get   https   longest   ble   pre   描述   def   

原文地址:https://www.cnblogs.com/Tang-tangt/p/9302355.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!