public class Solution { public string LongestCommonPrefix(string[] strs) { if (strs.Length == 0) { return ""; } else if (strs.Length == 1) { return strs[0]; } else { var maxLen = 1; var len = strs.Length; while (true) { for (int i = 0; i < len - 1; i++) { var s1 = strs[i]; var s2 = strs[i + 1]; if (s1.Length < maxLen || s2.Length < maxLen) { return strs[0].Substring(0, maxLen - 1); } if (s1.Substring(0, maxLen) != s2.Substring(0, maxLen)) { return strs[0].Substring(0, maxLen - 1); } } maxLen++; } } } }
https://leetcode.com/problems/longest-common-prefix/#/description
补充一个python的实现:
1 class Solution: 2 def longestCommonPrefix(self, strs: List[str]) -> str: 3 n = len(strs) 4 if n == 0: 5 return '' 6 if n == 1: 7 return strs[0] 8 j = 0 9 while True: 10 for i in range(1,n): 11 if j >= len(strs[i-1]) or j >= len(strs[i]): 12 return strs[i][:j] 13 if strs[i-1][j] != strs[i][j]: 14 return strs[i][:j] 15 j += 1 16 return strs[0][:j]