美文网首页leetcode-algorithm
leetcode-014 Longest Common Pref

leetcode-014 Longest Common Pref

作者: hylexus | 来源:发表于2016-10-05 00:11 被阅读15次

[TOC]

P014 Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

思路分析

题目本身并不难,最直观的就是逐个字符比较。操作下标很费劲。

  • 最长前缀的长度不会超过某个字符串的长度

代码

java

public class Solution014 {
    public String longestCommonPrefix(String[] strs) {
        StringBuilder sb = new StringBuilder();
        if (strs == null || strs.length == 0)
            return "";
        if (strs.length == 1)
            return strs[0];
        for (int i = 0; i < strs[0].length(); i++) {
            char c = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j++) {
                if (strs[j].length() == i || c != strs[j].charAt(i)) {
                    return sb.toString();
                }
            }
            sb.append(c);
        }
        return sb.toString();
    }

}

python

class Solution014(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        l = len(strs)
        if not strs or l == 0:return ""
        if l == 1:return strs[0]
        
        ret = ""
        for i in range(0, len(strs[0])):
            c = strs[0][i]
            for j in range(1, l):
                if len(strs[j]) == i or c != strs[j][i]:
                    return ret
            ret += c;
            
        return ret

相关文章

网友评论

    本文标题:leetcode-014 Longest Common Pref

    本文链接:https://www.haomeiwen.com/subject/qzssyttx.html