14. Longest Common Prefix

题目:

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

链接:http://leetcode.com/problems/longest-common-prefix/

一刷:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ''
        length = len(strs[0])
        common_prefix = ['']
        chars_at_idx = set()

        for idx in range(length):
            for one_string in strs:
                if len(one_string) <= idx:
                    return ''.join(common_prefix)
                chars_at_idx.add(one_string[idx])
            if len(chars_at_idx) != 1:
                return ''.join(common_prefix)
            common_prefix.append(chars_at_idx.pop())

        return ''.join(common_prefix)

可以减少中间变量和数据结构的使用:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ''
        length = len(strs[0])

        for idx in range(length):
            char = strs[0][idx]
            for one_string in strs:
                if len(one_string) <= idx or one_string[idx] != char:
                    return one_string[:idx]
        return strs[0]

2/9/2017, Java

这道题不难,主要是内层循环判断条件有些问题,还有最开始的输入判断因为不了解Java给删掉了,其实是需要保留的。

 1 public class Solution {
 2     public String longestCommonPrefix(String[] strs) {
 3         if (strs.length == 0) return "";
 4         if (strs.length == 1) return strs[0];
 5         char a;
 6         for(int i = 0; i < strs[0].length(); i++) {
 7             a = strs[0].charAt(i);
 8             for(int j = 1; j < strs.length; j++) {
 9                 if (strs[j].length() < i+1 || strs[j].charAt(i) != a) {
10                     return strs[0].substring(0, i);
11                 }
12             }
13         }
14         return strs[0];
15     }
16 }

 

posted @ 2016-06-03 11:17  panini  阅读(215)  评论(0编辑  收藏  举报