Python 3.x leetcode 14 python中最长公共前缀Java子字符串等效项

Python 3.x leetcode 14 python中最长公共前缀Java子字符串等效项,python-3.x,find,substring,Python 3.x,Find,Substring,编写一个函数,在字符串数组中查找最长的公共前缀字符串 如果没有公共前缀,则返回空字符串“” 例1: 输入:[“花”、“流”、“飞行”] 输出:“fl” 例2: 输入:[“狗”、“赛车”、“汽车”] 输出:“” 说明:输入字符串之间没有公共前缀。 注: 所有给定输入均以小写字母a-z表示。] 我目前的解决方案是: the algo here is to take the first element in the list and compare it to the other elements

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

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

例1:

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

输入:[“狗”、“赛车”、“汽车”] 输出:“” 说明:输入字符串之间没有公共前缀。 注:

所有给定输入均以小写字母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” 但它在测试用例中会失败[“abab”、“aba”、“abc”]

输出: “a”

预期: “ab”

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

>>> prefix='abab'
>>> strs='aba'
>>> strs.find(prefix)
-1
我想知道python中是否有Java等效函数“substring”可以工作

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

类解决方案{
公共字符串longestCommonPrefix(字符串[]strs){
如果(strs.length==0)返回“”;
字符串前缀=strs[0];

对于(inti=1;i我认为在python中,可以使用开始索引和结束索引来获取子字符串。 Like:val[1:3]

>>> prefix='abab'
>>> strs='aba'
>>> strs.find(prefix)
-1
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;
    }
}