題目: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 == null || strs.length == 0) { return ""; } String prefix = strs[0]; for (int i = 1; i < strs.length; i++) { int j = 0; while (j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j)) { j++; } if (j == 0) { return ""; } prefix = prefix.substring(0, j); } return prefix; } }