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

Longest Common Prefix

时间:2015-01-31 12:06:54      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

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

即找出一组字符串的最长公共前缀。

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        int min_size = Integer.MAX_VALUE;
        int n = strs.length;
        if(n == 0){
            return "";
        }
        for(int i = 0;i < n;i++){
            //若存在空串则返回"";
            if(strs[i].length() == 0){
                return "";
            }
            if(strs[i].length()<min_size){
                min_size = strs[i].length();//求得最短串的长度
            }
        }
        String re="";
        for(int j = 0;j < min_size;j++){
            char c = strs[0].charAt(j);
            for(int k = 0;k < n;k++){
                if(strs[k].charAt(j)!=c){
                    return re;
                }
            }
            re = re+c;
        }
        return re;
        
    }
}

 

Longest Common Prefix

标签:

原文地址:http://www.cnblogs.com/mrpod2g/p/4263828.html

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