1. 程式人生 > >Longest Common Prefix

Longest Common Prefix

null stat The sys char class stc write efi

描述
Write a function to find the longest common prefix string amongst an array of strings.
分析
從位置 0 開始,對每一個位置比較所有字符串,直到遇到一個不匹配。

代碼

 1 public class LongestCommonPref {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5         String[] strs= {"aaaa1","","aaa3"};
6 System.out.println(longestCommonPref(strs)); 7 8 } 9 public static String longestCommonPref(String[] strs) { 10 int minlen=strs[0].length(); 11 int max=strs[0].length(); 12 for(int i=0;i<strs.length;i++) { 13 if(strs[i].length()==0) return null; 14 if
(minlen<strs[i].length()) 15 minlen=strs[i].length(); 16 } 17 18 for(int i=1;i<strs.length;i++) { 19 int temp=0; 20 for(int j=0; j<minlen;j++) { 21 if(strs[0].charAt(j)==strs[i].charAt(j)) 22 continue; 23 else
{ 24 temp=j; 25 break; 26 } 27 } 28 if(max>temp) max=temp; 29 } 30 return strs[0].substring(0, max); 31 } 32 33 34 }

Longest Common Prefix