[LeetCode] 14. Longest Common Prefix

题目链接:传送门

Description

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

Solution

题意:

给定一些字符串,求这些字符串的最长公共前缀

思路:

经典的LCP问题,做法也有很多,直接暴力,后缀数组,字典树,字符串hash等等

(1) 直接做(偷懒

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.size() == 0)  return "";   // missed at first
        int len = 0;
        for (int i = 0; i < strs[0].length(); i++) {
            char cur = strs[0][i];
            bool flag = true;
            for (int j = 1; j < strs.size(); j++) {
                if (strs[j].length() <= i || strs[j][i] != cur) {
                    flag = false;
                    break;
                }
            }
            if (flag)  len++;
            else  break;
        }
        return strs[0].substr(0, len);
    }
};

补充:

在官方Solution里面看到分治的思路,有点惊讶,确实没往分治这边想

The idea of the algorithm comes from the associative property of LCP operation. We notice that :

LCP(S1Sn)=LCP(LCP(S1Sk),LCP(Sk+1Sn))LCP(S_1 \ldots S_n) = LCP(LCP(S_1 \ldots S_k), LCP (S_{k+1} \ldots S_n))
, where LCP(S1Sn)LCP(S_1 \ldots S_n) is the longest common prefix in set of strings [S1Sn][S_1 \ldots S_n] , 1<k<n1 < k < n

以及二分的思路

posted @ 2018-02-15 01:52  酒晓语令  阅读(72)  评论(0编辑  收藏  举报