14. Longest Common Prefix

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

写一个函数(或方法)来寻找一个字符串数组中的最长公共前缀。

注释

"abcdefg"
"abcdefghijk"
"abcdfghijk"
"abcef"

上面的字符串数组的最长公共前缀就是"abc"。

 1     public String longestCommonPrefix(String[] strs) {
 2         if(strs == null || strs.length == 0)    return "";
 3         String pre = strs[0];
 4         int i = 1;
 5         while(i < strs.length){
 6             while(strs[i].indexOf(pre) != 0)
 7                 pre = pre.substring(0,pre.length()-1);
 8             i++;
 9         }
10         return pre;        
11     }
 
原文地址:https://www.cnblogs.com/wzj4858/p/7678975.html