码迷,mamicode.com
首页 > 编程语言 > 详细

求字符串数组最长公共前缀

时间:2016-05-26 18:57:00      阅读:411      评论:0      收藏:0      [点我收藏+]

标签:

public class LongestCommonPrefix {

    public String longestCommonPrefix(String[] strs)
    {
        if(strs == null)
            return null;
        if(strs.length == 0)
            return "";
        String s = strs[0];
        for(int i = 0; i < s.length(); i ++)
        {
            for(int j = 1; j < strs.length; j ++)
            {
                if(strs[j].length()==i||strs[j].charAt(i)!= s.charAt(i))//条件先后顺序不能写反了,否则数组越界
                    return s.substring(0,i);
            }
        }
        return s;
    }
    public static void main(String[] args) {
        LongestCommonPrefix lc = new LongestCommonPrefix();
        String[] strs = {"aa" , "a"};
        System.out.println(lc.longestCommonPrefix(strs));
    }

}

 

求字符串数组最长公共前缀

标签:

原文地址:http://www.cnblogs.com/masterlibin/p/5532012.html

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