首页 > 其他 > 详细

Longest Common Prefix

时间:2017-12-03 12:27:26      阅读:242      评论:0      收藏:0      [点我收藏+]
Write a function to find the longest common prefix string amongst an array of strings.

第二遍做法:时间复杂度应该是O(m*n),m表示字符串的最大长度,n表示字符串的个数,空间复杂度应该是O(m),即字符串的长度

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs==null || strs.length==0) return "";
        StringBuffer res = new StringBuffer();
        boolean isSame = true;
        for (int i=0; i<strs[0].length(); i++) {
            char cur = strs[0].charAt(i);
            for (int j=1; j<strs.length; j++) {
                if (i >= strs[j].length() || strs[j].charAt(i) != cur) {
                    isSame = false;
                    break;
                }
            }
            if (isSame) {
                res.append(cur);
            }
            else break;
        }
        return res.toString();
    }
}

  

Longest Common Prefix

原文:http://www.cnblogs.com/apanda009/p/7965501.html

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