Question:
Write a function to find the longest common prefix string amongst an array of strings.
Analysis:
写一个函数找到一个字符串数组的最长公共前缀。
思路:依次两两比较,用短的前缀更新比较长的前缀,一直到数组的末尾。
Answer:
public class Solution { public static String longestCommonPrefix(String[] strs) { if(strs.length == 0) return ""; if(strs.length == 1) return strs[0]; char[] res = strs[0].toCharArray(); for(int i=1; i<strs.length; i++) { char[] ch1 = strs[i-1].toCharArray(); char[] ch2 = strs[i].toCharArray(); char[] ch12 = getCommon(ch1, ch2); //System.out.println(ch12[0]); if(ch12.length == 1 && ch12[0] == ' ') return ""; if(ch12.length <= res.length) { res = ch12; } } return new String(res); } public static char[] getCommon(char[] ch1, char[] ch2) { int shorter = ch1.length <= ch2.length ? ch1.length : ch2.length; char[] prefix = new char[shorter]; int common = 0; for(int j=0; j<shorter; j++) { if(ch1[j] == ch2[j]) { common++; prefix[j] = ch1[j]; } else break; } char[] prefix1 = new char[common]; for(int i=0; i<common; i++) prefix1[i] = prefix[i]; return prefix1; } }