LeetCode简单题:14. 最长公共前缀(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/longest-common-prefix/
要点:字符串比较
Python,C++,Java用的方法相同
写一个两个string之间求最大公共前缀的函数
然后打擂台方法求出所有string的最大公共前缀

二.Python实现

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""
        
        prefix, count = strs[0], len(strs)
        for i in range(1, count):
            prefix = self.lcp(prefix, strs[i])
            if not prefix:
                break
        
        return prefix
    
    def lcp(self,str1,str2) -> str:
        length=min(len(str1),len(str2))
        index=0
        for i in range(0,length):
            if str1[i]==str2[i]:
                index+=1
            else:
                break

        return str1[:index]

三.C++实现

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

    string longestCommonPrefix(const string& str1, const string& str2) {
        int length = min(str1.size(), str2.size());
        int index = 0;
        for(int i=0;i

四.java实现

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String prefix = strs[0];
        int count = strs.length;
        for (int i = 1; i < count; i++) {
            prefix = longestCommonPrefix(prefix, strs[i]);
            if (prefix.length() == 0) {
                break;
            }
        }
        return prefix;
    }

    public String longestCommonPrefix(String str1, String str2) {
        int length = Math.min(str1.length(), str2.length());
        int index = 0;
        for(int i=0;i

你可能感兴趣的:(LeetCode简单题:14. 最长公共前缀(Python,C++,Java))