[Leetcode] Longest Common Prefix

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

 Solution:

第0个字符串和其他字符串逐个求前缀

对strs做了一个排序操作:Arrays.sort(strs);使得最终结果从492ms变成了468ms。

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         if(strs.length==0)
 4             return "";
 5         Arrays.sort(strs);
 6         String prefix=strs[0];
 7         for(int i=1;i<strs.length;++i){            
 8             int minLen=Math.min(prefix.length(), strs[i].length());
 9             int j=0;
10             for(;j<minLen;++j){
11                 if(prefix.charAt(j)!=strs[i].charAt(j))
12                     break;
13             }
14             prefix=prefix.substring(0, j);
15         }
16         return prefix;
17     }
18 }
原文地址:https://www.cnblogs.com/Phoebe815/p/4052101.html