头图

title: Daily Practice (35): Longest Common Prefix

categories:[Swords offer]

tags:[Daily practice]

date: 2022/03/14


Daily practice (35): Longest common prefix

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

If no common prefix exists, the empty string "" is returned.

Example 1:

Input: strs = ["flower","flow","flight"]

output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]

output: ""

Explanation: The input does not have a common prefix.

hint:

1 <= strs.length <= 200

0 <= strs[i].length <= 200

strs[i] consists of lowercase English letters only

Source: LeetCode

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

Method 1: Compare character by character

Thought analysis

Compare the first with the second, save the common prefix, then compare with the third, and so on

string longestCommonPrefix(vector<string>& strs) {
    if (strs.size() == 0) {
        return "";
    }
    string ans = strs[0];//先从strs[0]开始,与后面一个比较
    for (int i = 0; i < strs.size(); i++) {
        string s = ans;//保存上次的公共前缀
        ans = "";
        for (int j = 0; j < strs[i].size(); j++) {
            if (s[j] == strs[i][j]) {
                ans += s[j];
            } else { //遇到不一样的就退出循环
                break;
            }
        }
        if (ans == "") {
            break;
        }
    }
    return ans;
}

Method 2: Double pointer

Algorithm flow:

First find out the lexicographically smallest and largest strings in the array, and the longest common prefix is the common prefix of the two strings

string longestCommonPrefix(vector<string>& strs) {
    if (strs.size() == 0) {
        return "";
    }
    const auto p = minmax_element(strs.begin(), strs.end());
    for (int i = 0; i < p.first->size(); i++) {
        if (p.first->at(i) != p.second->at(i)) {
            return p.first->substr(0, i);
        }
    }
    return *p.first;
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记