Write a function to find the longest common prefix string amongst an array of strings.
- public class Solution {
- public String longestCommonPrefix(String[] strs) {
- if(strs.length==0) return "";
- boolean same = true;
- int minLen = 900000;
- for(int i=0;i<strs.length;i++){
- if(strs[i].length()<minLen) minLen = strs[i].length();
- }
- int index = 0;
- while(index<minLen){
- same = true;
- for(int i=0;i<strs.length-1;i++){
- if(strs[i].charAt(index)!=strs[i+1].charAt(index)){
- same = false;
- break;
- }
- }
- if(same) index++;
- else break;
- }
- if(minLen==0) return "";
- else{
- return strs[0].substring(0,index);
- }
- }
- }
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/45495683