在两个不同字符串的相同位置匹配子字符串?

2024-04-27 12:23:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试解决Python中的一个编码问题

以下是问题的定义:

Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.

string_match('xxcaazz', 'xxbaaz') → 3

string_match('abc', 'abc') → 2

string_match('abc', 'axc') → 0

以下是我的代码:

def string_match(a, b):
  count = 0
  for i in range(len(a)-1):
    for j in range(len(b)-1):
      if a[i:i+2] == b[j:j+2]:
        count += 1
  return count

上述代码的输出:

我无法找出我的代码出了什么问题

希望你能帮助我。期待回应


Tags: andthe代码inforstringreturnmatch
2条回答
def string_match(a, b):

    shorter = min(len(a), len(b))
    count = 0

    for i in range(shorter-1):
        a_sub = a[i:i+2]
        b_sub = b[i:i+2]
        if a_sub == b_sub:
        count = count + 1

    return count

这应该可以完成工作,通过所有测试用例

def string_match(a, b):
    found = 0
    for i in range(min([len(a), len(b)])-1):
        if a[i] == b[i] and a[i+1] == b[i+1]:
            found += 1
    return found

print(string_match('iaxxai', 'aaxxaaxx'))

您不需要拆分字符串,只需要检查ii + 1处的字符是否相等。如果要检查n长度,可能需要一个内部循环。它也适用于len(a) != len(b)

相关问题 更多 >