繁体   English   中英

在两个不同字符串的同一位置匹配 substring?

[英]Matching substring in the same place on two different strings?

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

这是问题定义:

给定 2 个字符串 a 和 b,返回它们包含相同长度 2 substring 的位置数。 所以 "xxcaazz" 和 "xxbaaz" 得到 3,因为 "xx"、"aa" 和 "az" 子字符串出现在两个字符串中的相同位置。

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

上述代码中的 output:

我无法弄清楚我的代码有什么问题。

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

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

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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM