[One question per day] The longest common prefix

https://leetcode-cn.com/problems/longest-common-prefix/

Write a function to find the longest common prefix in a string array.

If there is no public prefix, the empty string "" is returned.

Example 1:

Input: [“flower”, “flow”, “flight”]
Output: “fl”
Example 2:

Input: ["dog", "racecar", "car"]
Output: ""
Explanation: There is no common prefix in the input.
Explanation:

All input contains only lowercase letters az.


Solution 1

4ms, 6.6mb
brute force, first find the shortest string length, then iterate over each character of each string, and add to the result if they are equal.

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.size() == 0) {
            return "";
        }

        // 找出最短的字符串长度
        int min_len = strs[0].size();
        for (int i = 1; i < strs.size(); ++i) {
            if (strs[i].size() <= min_len) {
                min_len = strs[i].size();
            }
        }

        // 找出公共字符并加到 res 上
        string res = "";
        for (int i = 0; i < min_len; ++i) {
            char c = strs[0][i];
            for (int j = 1; j < strs.size(); ++j) {
                if (c != strs[j][i]) {
                    return res;
                }
            }
            res += c;
        }

        return res;
    }
};

Solution 2

Violence is nothing but subtraction. 4ms, 6.9mb
Assuming that the first string is the longest common prefix, traverse each character of other strings, and break if it encounters a different one.

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

        return res;
    }
};

EOF

98 original articles have been published · 91 praises · 40,000+ views

Guess you like

Origin blog.csdn.net/Hanoi_ahoj/article/details/105314976