14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
求多个字符串的最长公共前缀。
public class Solution { public String longestCommonPrefix(String[] strs) { if (strs.length == 0) return ""; for (int i = 0; i < strs[0].length(); i++) { for (int j = 1; j < strs.length; j++) if (strs[j].length() <= i || strs[j].charAt(i) != strs[0].charAt(i)) return strs[0].substring(0, i); } return strs[0]; } }
1、当strs为空,直接输出“”
2、当strs中含有“”,直接输出“”
3、strs[0]的最长长度由最短公共长度l决定(code line:15)
class Solution: # @return a string def longestCommonPrefix(self, strs): if strs == []: return "" for i in range(1,len(strs)): l1 = len(strs[0]) l2 = len(strs[i]) if l1>l2: l = l2 else: l = l1 if l==0: return "" strs[0]=strs[0][0:l] for j in range(l): if strs[0][j] != strs[i][j]: strs[0] = strs[0][0:j] break return strs[0]