public class Solution {
public string LongestCommonPrefix(string[] strs) {
if (strs.Length == )
{
return "";
}
else if (strs.Length == )
{
return strs[];
}
else
{
var maxLen = ; var len = strs.Length;
while (true)
{
for (int i = ; i < len - ; i++)
{
var s1 = strs[i];
var s2 = strs[i + ]; if (s1.Length < maxLen || s2.Length < maxLen)
{
return strs[].Substring(, maxLen - );
} if (s1.Substring(, maxLen) != s2.Substring(, maxLen))
{
return strs[].Substring(, maxLen - );
}
}
maxLen++;
}
}
}
}

https://leetcode.com/problems/longest-common-prefix/#/description

补充一个python的实现:

 class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
n = len(strs)
if n == :
return ''
if n == :
return strs[]
j =
while True:
for i in range(,n):
if j >= len(strs[i-]) or j >= len(strs[i]):
return strs[i][:j]
if strs[i-][j] != strs[i][j]:
return strs[i][:j]
j +=
return strs[][:j]
04-27 01:50