[LeetCode]-011-Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

[]
=>""
["abcweed","htgdabc","sabcrf"]
=>""
["abcweed","abhtgdc","abacrf"]
=>"ab"

题目大意:求字符串数组的最长子前缀

 1 public class Solution{
 2     public String longestCommonPrefix(String[] strs) {
 3         //System.out.println(Arrays.toString(strs));
 4         if(strs.length == 0)
 5             return "";
 6         int min = Integer.MAX_VALUE;
 7         for(String s : strs){
 8             if(min>s.length())
 9                 min = s.length();
10         }
11         if(min==0)
12             return "";
13         //System.out.println(min);
14         String prefix = "", tmp = "";
15         int i=0;
16         for( ; i<min; i++){
17             prefix = strs[0].substring(0,(i+1));
18             //System.out.println("prefix=" + prefix);
19             for(int j=1; j<strs.length; j++){
20                 tmp = strs[j].substring(0,(i+1));
21                 //System.out.println("tmp=" + tmp);
22                 if(!prefix.equals(tmp))
23                     return strs[0].substring(0,(i));
24             }
25         }
26         System.out.println("i=" + strs[0].substring(0,(i)));
27         return "";
28     }
29     
30     
31     public static void main(String[] args){
32         String[] arr = {"","asdffg","aswd"};
33         if(args.length!=0)
34             arr = args;
35         Solution solution = new Solution();
36         String res = solution.longestCommonPrefix(arr);
37         System.out.println(res);
38     }
39 }

 

posted @ 2016-04-18 11:00  练子  阅读(152)  评论(0编辑  收藏  举报