lintcode 最长公共前缀

作者: yzawyx0220 | 来源:发表于2017-01-13 11:02 被阅读174次

给k个字符串,求出他们的最长公共前缀(LCP)
样例
在 "ABCD" "ABEF" 和 "ACEF" 中, LCP 为 "A"
在 "ABCDEFG", "ABCEFG", "ABCEFA" 中, LCP 为 "ABC"
题目链接:http://www.lintcode.com/zh-cn/problem/longest-common-prefix/
方法比较简单,就是一次比较每个字符,如果都相等,那么长度加1.

class Solution {
public:    
    /**
     * @param strs: A list of strings
     * @return: The longest common prefix
     */
    string longestCommonPrefix(vector<string> &strs) {
        // write your code here
        string res;
        if (strs.size() == 0) return "";
        for (int i = 0;i < strs[0].size();i++) {
            int j = 1;
            for (j;j < strs.size();j++) {
                if (strs[0][i] != strs[j][i]) return res;
            }
            if (j == strs.size()) res = res + strs[0][i];
        }
        return res;
    }
};

相关文章

  • lintcode 最长公共前缀

    给k个字符串,求出他们的最长公共前缀(LCP)样例在 "ABCD" "ABEF" 和 "ACEF" 中, LCP...

  • lintcode 78. 最长公共前缀

    难度:中等 1. Descriprion 2. Solution 注意特殊情况: strs = "" strs中有...

  • LeetCode 每日一题 [19] 最长公共前缀

    LeetCode 最长公共前缀 [简单] 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回...

  • 14. 最长公共前缀

    20180923-摘抄自14. 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,...

  • 5,最长公共前缀/数组与字符串

    最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1:...

  • Swift 最长公共前缀 - LeetCode

    题目: 最长公共前缀 描述: 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""...

  • leetcode探索之旅(14)

    最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。 示例 1: ...

  • Leetcode 14 最长公共前缀

    最长公共前缀 题目 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例...

  • LeetCodeSwift 14.Longest Common

    题目 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例...

  • [day4] [LeetCode] [title14,122]

    14.最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串""。 示例 ...

网友评论

本文标题:lintcode 最长公共前缀

本文链接:https://www.haomeiwen.com/subject/aatsbttx.html