两个字符串python之间的交集

时间:2015-08-29 21:38:28

标签: python string substring

这是指用Java完成的问题:
Finding the intersection between two list of string candidates

我试图在python中找到一个等效的解决方案:

def solution(S):
    length = len(S)
    if length == 0:
        return 1
    count = 0
    i = 0
    while i <= length:
        prefix = S[0:i:]
        suffix = S[length-i:length]
        print suffix
        if prefix == suffix:
            count += 1
        i += 1
    return count

print solution("")
print solution("abbabba")    
print solution("codility")

我知道我在后缀方面没有采取措施。

我得到的值是1,4,2而不是1,4,0​​

1 个答案:

答案 0 :(得分:2)

您当前的代码通过为后两个示例提供以下前缀,后缀对来运行:

a a
ab ba
abb bba
abba abba
abbab babba
abbabb bbabba
abbabba abbabba

c y
co ty
cod ity
codi lity
codil ility
codili dility
codilit odility
codility codility

我假设您正在尝试返回字符串的第一个n字符与上一个n相同的次数。单词codility返回2的原因是因为您从零开始索引,因此它匹配空字符串和完整字符串。请尝试改为:

def solution(S):
    length = len(S)
    if length == 0:
        return 1
    count = 0
    i = 1 # Don't test the empty string!
    while i < length: # Don't test the whole string! Use '<'
        prefix = S[:i] # Up to i
        suffix = S[length-i:] # length - i to the end
        print prefix, suffix
        if prefix == suffix:
            count += 1
        i += 1
    return count

print solution("")
print solution("abbabba")    
print solution("codility")

返回1,2,0。

也许您正在测试前缀是否与后缀向后相同,并且只测试字符串长度的一半?在这种情况下,您应该尝试以下方法:

def solution(S):
    length = len(S)
    if length == 0:
        return 1
    count = 0
    i = 1 # Don't test the empty string!
    while i <= (length + 1)/2: # Test up to halfway
        prefix = S[:i] # Up to i
        suffix = S[:length-i-1:-1] # Reverse string, up to length - i - 1
        print prefix, suffix
        if prefix == suffix:
            count += 1
        i += 1
    return count

print solution("")
print solution("abbabba")    
print solution("codility")

返回1,4,0​​。