凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 14. Longest Common Prefix

分类:algorithm| 发布时间:2016-07-02 15:49:00


题目

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

题意

找出一组字符串的最长公共前缀。

解法 1

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.empty()) {
            return string();
        }

        string ret = strs[0];
        int retSize = ret.size();
        const int size = strs.size();
        for (int i = retSize - 1; i >= 0; --i) {
            for (int j = 1; j < size; ++j) {
                if (strs[j].size() < i + 1 || strs[j][i] != ret[i]) {
                    retSize = i;
                    break;
                }
            }
        }

        ret.resize(retSize);
        return ret;
    }
};

解法 2

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.empty()) return "";
        string res="";
        int i = 0;
        while (true) {
            for (int j = 0; j < strs.size(); j++) {
                if (i == strs[j].size() || strs[j][i] != strs[0][i]) {
                    return res;
                }
            }

            res +=strs[0][i];
            i++;
        }
    }
};