Longest Common Prefix

Posted apanda009

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
    }
}

  

以上是关于Longest Common Prefix的主要内容,如果未能解决你的问题,请参考以下文章

1143. Longest Common Subsequence

1143. Longest Common Subsequence

leetcode14. longest common prefix

LintCode Longest Common Subsequence

LintCode Longest Common Substring

#Leetcode# 14. Longest Common Prefix