标签:
https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings
1 public class Solution { 2 public static String longestCommonPrefix(String[] strs) { 3 if(strs.length==0){return "";} 4 if(strs.length==1){return strs[0];} 5 int len=strs.length; 6 int index=0; 7 boolean flag=false; 8 for(int i=0;i<strs[0].length();i++){ 9 char x=strs[0].charAt(i); 10 for(int j=1;j<len;j++){ 11 if(i>=strs[j].length()){flag=true;index=i;break;} 12 char y=strs[j].charAt(i); 13 if(x!=y){flag=true;index=i;break;} 14 } 15 if(flag){break;} 16 if(i==strs[0].length()-1){index=strs[0].length();} 17 } 18 String ans=strs[0].substring(0,index); 19 return ans; 20 } 21 public static void main(String[]args){ 22 String[]strs=new String[2]; 23 strs[0]="a"; 24 strs[1]="a"; 25 System.out.println(longestCommonPrefix(strs)); 26 } 27 }
标签:
原文地址:http://www.cnblogs.com/qq1029579233/p/4477959.html