【算法】14. 最长公共前缀(多语言实现)

118 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 19 天,点击查看活动详情


14. 最长公共前缀:

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

样例 1:

输入:
	strs = ["flower","flow","flight"]
	
输出:
	"fl"

样例 2:

输入:
	strs = ["dog","racecar","car"]
	
输出:
	""
	
解释:
	输入不存在公共前缀。
	

提示:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] 仅由小写英文字母组成

原题传送门:

leetcode.cn/problems/lo…


分析

  • 面对这道算法题目,二当家的陷入了沉思。
  • 公共前缀,就是每个字符串的相同前缀。
  • 可以先看所有字符串的第一个字符是否相同,如果相同再看下一个,直到最短字符串的长度或者遇到字母不同。
  • 也可以先找到第一个和第二个字符串的公共前缀,再用它和第三个字符串找公共前缀,直到结束。

题解

rust

impl Solution {
    pub fn longest_common_prefix(strs: Vec<String>) -> String {
        strs.split_first().map(|(first, tail)| {
            tail.iter().fold(first.as_str(), |ans, s| {
                &ans[0..s.as_bytes().iter()
                    .zip(ans.as_bytes())
                    .take_while(|(x, y)| x == y)
                    .count()]
            }).to_string()
        }).unwrap()
    }
}

go

func longestCommonPrefix(strs []string) string {
    ans := strs[0]
    l := len(strs)
    for i := 1; i < l; i++ {
        str := strs[i]
        index := 0
        var size int
        if len(ans) < len(str) {
            size = len(ans)
        } else {
            size = len(str)
        }
        for index < size && ans[index] == str[index] {
            index++
        }
        ans = ans[0:index]
    }
    return ans
}

c++

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string ans = strs[0];
        for (int i = 1; i < strs.size(); ++i) {
            string str = strs[i];
            int size = min(ans.size(), str.size());
            int index = 0;
            while (index < size && ans[index] == str[index]) {
                ++index;
            }
            ans = ans.substr(0, index);
        }
        return ans;
    }
};

java

class Solution {
    public String longestCommonPrefix(String[] strs) {
        String ans = strs[0];
        for (int i = 1; i < strs.length; ++i) {
            String str   = strs[i];
            int    size  = Math.min(ans.length(), str.length());
            int    index = 0;
            while (index < size && ans.charAt(index) == str.charAt(index)) {
                ++index;
            }
            ans = ans.substring(0, index);
        }
        return ans;
    }
}

typescript

function longestCommonPrefix(strs: string[]): string {
    let ans = strs[0];

    for (let i = 1; i < strs.length; ++i) {
        const str = strs[i];
        const size = Math.min(ans.length, str.length);
        let index = 0;
        while (index < size && ans[index] === str[index]) {
            ++index;
        }
        ans = ans.substring(0, index);
    }

    return ans;
};

python

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        ans = strs[0]
        for i in range(1, len(strs)):
            str = strs[i]
            size = min(len(ans), len(str))
            index = 0
            while index < size and ans[index] == str[index]:
                index += 1
            ans = ans[:index]
        return ans


非常感谢你阅读本文~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~


开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 19 天,点击查看活动详情