我一直在尝试解决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
上述代码的输出:
我无法找出我的代码出了什么问题
希望你能帮助我。期待回应
这应该可以完成工作,通过所有测试用例
您不需要拆分字符串,只需要检查
i
和i + 1
处的字符是否相等。如果要检查n
长度,可能需要一个内部循环。它也适用于len(a) != len(b)
相关问题 更多 >
编程相关推荐