Longest Common Prefix

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

  

posted @ 2017-12-03 10:27  apanda009  阅读(155)  评论(0编辑  收藏  举报