Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在两个字符串中找到最多的共享字符?(Python)_Python_String - Fatal编程技术网

如何在两个字符串中找到最多的共享字符?(Python)

如何在两个字符串中找到最多的共享字符?(Python),python,string,Python,String,我不太确定如何在两个字符串之间找到最多共享字符数。例如(上面的字符串),最多共享的字符数是“yamxx”,长度为5个字符 xx不是一个解决方案,因为这不是最多的共享字符数。在这种情况下,最大的是yamxx,它有5个字符长,因此输出为5个字符 我对python和堆栈溢出非常陌生,因此非常感谢您的帮助 注意:它们在两个字符串中的顺序应该相同这里是使用动态规划的简单、有效的解决方案 def最长_子字符串(X,Y): m、 n=len(X),len(Y) LCSuff=[[0表示范围(n+1)中的k]表

我不太确定如何在两个字符串之间找到最多共享字符数。例如(上面的字符串),最多共享的字符数是“yamxx”,长度为5个字符

xx不是一个解决方案,因为这不是最多的共享字符数。在这种情况下,最大的是yamxx,它有5个字符长,因此输出为5个字符

我对python和堆栈溢出非常陌生,因此非常感谢您的帮助


注意:它们在两个字符串中的顺序应该相同这里是使用动态规划的简单、有效的解决方案

def最长_子字符串(X,Y):
m、 n=len(X),len(Y)
LCSuff=[[0表示范围(n+1)中的k]表示范围(m+1)中的l]
结果=0
对于范围(m+1)内的i:
对于范围(n+1)内的j:
如果(i==0或j==0):
LCSuff[i][j]=0
elif(X[i-1]==Y[j-1]):
LCSuff[i][j]=LCSuff[i-1][j-1]+1
结果=最大值(结果,LCSuff[i][j])
其他:
LCSuff[i][j]=0
打印(结果)
最长的子字符串(“abcd”、“arcd”)#打印2
最长的子字符串(“yammxdj”、“nhjdyammx”)#打印5

此解决方案从尽可能长的子字符串开始。如果对于某个长度,不存在该长度的匹配子字符串,则它将移动到下一个较低的长度。这样,它可以在第一场成功的比赛中停止

yamxxopd
yndfyamxx

Output: 5
输出:

答案是5

s1=“yamxxopd”
s2=“yndfyamxx”
#初始化计数器
计数器=0
#不重复地创建和初始化字符串
s=“”
对于s1中的x:
如果x不在s中:
s=s+x
对于s中的x:
如果s2中的x:
计数器=计数器+1
#显示两个字符串s1和s2中最多共享字符数

打印(计数器)#显示5
它们在两个字符串中的顺序应该相同?您正在查找最长的匹配子字符串。是的,它们在两个字符串中的顺序应该相同。最简单的方法就是循环并尝试匹配,直到失败。然后将其报告为长度。例如,在
y n d f y a m x
的每个位置,最长的匹配是
1 0 1 0 5 4 3 2 1
。最大值为
5
,因此您要报告出现在那里的子字符串(
y a m x
)。请从中重复和。“演示如何解决此编码问题?”与堆栈溢出无关。您必须诚实地尝试解决方案,然后询问有关实现的具体问题。
s_1 = "yamxxopd"
s_2 = "yndfyamxx"

l_1, l_2 = len(s_1), len(s_2)

found = False
sub_length = l_1                                 # Let's start with the longest possible sub-string
while (not found) and sub_length:                # Loop, over decreasing lengths of sub-string
    for start in range(l_1 - sub_length + 1):    # Loop, over all start-positions of sub-string
        sub_str = s_1[start:(start+sub_length)]  # Get the sub-string at that start-position
        if sub_str in s_2:                       # If found a match for the sub-string, in s_2
            found = True                         # Stop trying with smaller lengths of sub-string
            break                                # Stop trying with this length of sub-string
    else:                                        # If no matches found for this length of sub-string
        sub_length -= 1                          # Let's try a smaller length for the sub-strings

print (f"Answer is {sub_length}" if found else "No common sub-string")