14. 最长公共前缀 Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Input: strs = ["flower","flow","flight"]
Output: "fl"
public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) return ""; int minLen = strs[0].length(); for (int i = 1; i < strs.length; i++){ minLen = Math.min(minLen, strs[i].length()); } StringBuilder ans = new StringBuilder(); for (int i = 0; i < minLen; i++){ for (int j = 1; j < strs.length; j ++){ if (strs[j].charAt(i) != strs[0].charAt(i)) return ans.toString(); } ans.append(strs[0].charAt(i)); } return ans.toString(); }
参考链接:
https://leetcode.com/problems/longest-common-prefix/
https://leetcode-cn.com/problems/longest-common-prefix/