码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Common Prefix

时间:2015-05-04 23:58:12      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Longest Common Prefix

标签:

原文地址:http://www.cnblogs.com/qq1029579233/p/4477959.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!