Longest Common Prefix

描述
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 }
原文地址:https://www.cnblogs.com/ncznx/p/9190738.html