首页 > 其他 > 详细

Longest Common Prefix

时间:2016-02-25 22:44:13      阅读:248      评论:0      收藏:0      [点我收藏+]

package cn.edu.xidian.sselab.string;

/**
 *
 * @author zhiyong wang
 * title: Longest Common Prefix
 * content:
 *
 *Write a function to find the longest common prefix string amongst an array of strings.
 */
public class LongestCommonPrefix {

    //把第一个字符串作为前缀来判断,然后从第二个字符串开始遍历,如果他的indexOf不等于0,说明第一个字符串不是他的前缀,
    //这个时候,将第一个字符串的最后一位去掉来作为前缀继续判断,直到该字符串是他的前缀为止,然后判断他是否是下一个的前缀,时间复杂度为O(N)
    public String longestCommonPrefix(String[] strs){
        if(strs == null || strs.length == 0) return "";
        String pre = strs[0];
        int i = 1;
        while(i < strs.length){
            while(strs[i].indexOf(pre) != 0)
                pre = pre.substring(0,pre.length() - 1);
            i++;
        }
        return pre;
    }
    
}

Longest Common Prefix

原文:http://www.cnblogs.com/wzyxidian/p/5218441.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!