leetcode 14 python中等效的最长公共前缀Java子字符串

时间:2020-02-22 21:07:55

标签: python-3.x find substring

编写一个函数以在字符串数组中找到最长的公共前缀字符串。

如果没有公共前缀,则返回一个空字符串“”。

示例1:

输入:[“花”,“流”,“飞行”] 输出:“ fl” 示例2:

输入:[“ dog”,“ racecar”,“ car”] 输出:“” 说明:输入字符串之间没有公共前缀。 注意:

所有给定的输入均使用小写字母a-z。]

我当前的解决方案是:

the algo here is to take the first element in the list and compare it to the other elements

if the prefixes are different, then reduce the word from the end

flower vs flow => reduce r from flower

flowe vs flow => reduce e from flowe

flow vs flow => the same. stop

它适用于此测试用例:

输入:[“花”,“流”,“飞行”]

输出:“ fl”

class Solution:

    def longestCommonPrefix(self, strs: List[str]) -> str:




        if len(strs) == 0:

            return ""

        prefix = strs[0]

        for i in range(1,len(strs), 1):

            while (strs[i].find(prefix) != 0): # use the function "find" to compare the next word "strs[i] and 'prefix'. If any difference, return the number of element that is different 

                prefix=prefix[:-i]

        return prefix

但是在测试用例[“ abab”,“ aba”,“ abc”]中会失败

输出: “ a”

预期: “ ab”

这是因为当前缀长于其他元素并返回-1时,查找将不起作用

>>> prefix='abab'
>>> strs='aba'
>>> strs.find(prefix)
-1

我想知道python中是否有任何Java等效函数“ substring”会起作用?

此Java解决方案适用于“子字符串”

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) return "";
        String prefix = strs[0];
        for (int i=1; i<strs.length; i++)
        {
            while (strs[i].indexOf(prefix) !=0)

            {
                prefix = prefix.substring(0, prefix.length()-1);

            }

        }

        return prefix;
    }
}

2 个答案:

答案 0 :(得分:0)

我认为在python中,您可以仅使用开始索引和结束索引来获取子字符串。 像:val [1:3]

答案 1 :(得分:0)

使用数据框和 iloc 将结果行切片为数据值的字符串段。检查结果集在哪里 1 意味着切片都是重复的并将它们添加到列表中。在列表中找到最大大小的字符串。

data=['flower','flow','flight']
min_length=min([len(x) for x in data])
df=pd.DataFrame(data,columns=['data'])    
results=[]    
for i in range(1,min_length):
   alist=[]
   alist=(df.iloc[0:min_length]['data'].str[0:i])

   if len(set(alist))==1:
          results.append(set(alist))
 print(max([x.pop() for x in results],key=len))

输出

fl