LeetCode14. Longest Common Prefix

Posted wilderness

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode14. Longest Common Prefix相关的知识,希望对你有一定的参考价值。

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

题意:找出所给几个字符串的相同前缀

思路:用第一个字符串和之后的所有字符串进行对比,标示出相同字符串的超尾指针就行

ps:通过这个题发现自己Python基础好差啊

 1 class Solution(object):
 2     def longestCommonPrefix(self, strs):
 3         """
 4         :type strs: List[str]
 5         :rtype: str
 6         """
 7         if len(strs)==0: return ‘‘
 8         str = strs[0]
 9         min = len(str)
10         for i in range(1, len(strs)):
11             j=0
12             tmp = strs[i]
13             while j<min and j<len(tmp) and str[j] == tmp[j]:
14                 j+=1
15             if j<min: min = j
16         
17         return str[:min]

 耗时84ms,排名太靠后了,不能忍

 1 class Solution(object):
 2     def longestCommonPrefix(self, strs):
 3         """
 4         :type strs: List[str]
 5         :rtype: str
 6         """
 7         if len(strs)==0: return ‘‘
 8         str = strs[0]
 9         min = len(str)
10         for tmp in strs[1:]:
11             j=0
12             while j<min and j<len(tmp) and str[j]==tmp[j]:
13                 j+=1
14             if j<min: min=j
15         
16         return str[:min]

 耗时59ms,好了点,但还是不理想

 1 class Solution(object):
 2     def longestCommonPrefix(self, strs):
 3         """
 4         :type strs: List[str]
 5         :rtype: str
 6         """
 7         if len(strs)==0: return ‘‘
 8         str = strs[0]
 9         min = len(str)
10         for tmp in strs[1:]:
11             j = 0
12             l = len(tmp)
13             while j<min and j<l and str[j]==tmp[j]:
14                 j+=1
15             if j<min: min=j
16         
17         return str[:min]

把重复计算的min = len(str)保存后,变成了49ms,len()耗时挺长啊,感觉还能继续改

 1 class Solution(object):
 2     def longestCommonPrefix(self, strs):
 3         """
 4         :type strs: List[str]
 5         :rtype: str
 6         """
 7         if len(strs)==0: return ‘‘
 8         str = strs[0]
 9         min = len(str)
10         for tmp in strs[1:]:
11             j = 0
12             l = len(tmp)
13             while j<min and j<l and str[j]==tmp[j]:
14                 j+=1
15             min=j     #不用判断,j的值肯定小于min,直接更新
16         
17         return str[:min]

又减了4ms

感觉还能改,但是不知道怎么改了。。。

没办法,

只有这样了。。

!!!!

0ms

 1 char* longestCommonPrefix(char** strs, int strsSize) {
 2     if(!strsSize) return "";
 3     char *str=strs[0];
 4     int i,j;
 5     for(i=1;i<strsSize;i++){
 6         j=0;
 7         while(str[j]&&strs[i][j]&&str[j]==strs[i][j])
 8             j++;
 9         str[j]=\0;
10     }
11     return str;
12 }

 

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

leetcode14. longest common prefix

Leetcode 14. Longest Common Prefix

Leetcode 14 Longest Common Prefix

Leetcode14. Longest Common Prefix

LeetCode 14: Longest Common Prefix

leetcode 14. Longest Common Prefix