#力扣:14. 最长公共前缀@FDDLC

14. 最长公共前缀

一、Java

class Solution {
    public String longestCommonPrefix(String[] strs) {
        for (int l = 0; ; l++) {
            for (int i = 0; i < strs.length; i++) {
                if (l >= strs[i].length() || strs[i].charAt(l) != strs[0].charAt(l)) return strs[0].substring(0, l);
            }
        }
    }
}

二、C++

#include 
#include 

using namespace std;

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

三、Python

from typing import List


class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        l = 0
        while True:
            for i in range(len(strs)):
                if l >= len(strs[i]) or strs[i][l] != strs[0][l]:
                    return strs[0][0:l]
            l += 1

四、JavaScript

var longestCommonPrefix = function (strs) {
    for (let l = 0; ; l++) {
        for (let i = 0; i < strs.length; i++) {
            if (l >= strs[i].length || strs[i][l] != strs[0][l]) return strs[0].substring(0, l);
        }
    }
};

五、Go

package main

func longestCommonPrefix(strs []string) string {
	for l := 0; ; l++ {
		for i := 0; i < len(strs); i++ {
			if l >= len(strs[i]) || strs[i][l] != strs[0][l] {
				return strs[0][0:l]
			}
		}
	}
}

你可能感兴趣的:(力扣刷题:Java,C++,Python,JS,Go,leetcode,算法,职场和发展)