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

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));
    }

}

 

posted @ 2016-05-26 17:33  32ddd  阅读(263)  评论(0编辑  收藏  举报