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

Longest Common Prefix

时间:2014-11-10 19:53:49      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   sp   for   div   on   

Longest Common Prefix

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

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         String result = "";
 4         if(null == strs || 0 == strs.length)
 5             return result;
 6     
 7         int minLength = strs[0].length();
 8         boolean end = false;
 9         for(int i = 1; i < strs.length; i++){
10             minLength = minLength > strs[i].length() ? strs[i].length() : minLength;
11         }//找出最小长度
12         for(int i = 0; i < minLength && !end; i++){
13             char ch = strs[0].charAt(i);//第i个字符
14             for(int j = 1; j < strs.length;j++){//遍历所有字符串
15                 if(strs[j].charAt(i) != ch){
16                     end = true;
17                 }
18             }
19             if(!end)
20                 result += ch;
21         }
22         return result;
23     }
24 }

 

Longest Common Prefix

标签:style   blog   io   color   ar   sp   for   div   on   

原文地址:http://www.cnblogs.com/luckygxf/p/4087864.html

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