刷抖音碰到一个题目
两个字符串比较,如abcdefg和25abdfxx,返回:位置0多出:25;位置2缺少:c;位置4缺少:e;位置6错误,应为g。
def compare_strings(str1, str2): len1 = len(str1) len2 = len(str2) idx1 = 0 idx2 = 0 for i in range(len1): for j in range(idx2, len2): if str1[i] == str2[j]: if j > idx2 and i == idx1: print(f"位置{i}多出:{str2[idx2:j]}") idx1 += 1 idx2 = j + 1 elif i > idx1 and j == idx2: print(f"位置{idx1}缺少:{str1[idx1:i]}") idx1 = i + 1 idx2 += 1 elif i > idx1 and j > idx2: print(f"位置{idx1}错误,应为:{str1[idx1:i]}") idx1 = i + 1 idx2 = j + 1 else: idx1 += 1 idx2 += 1 break if i == (len1 - 1) and (idx1 < len1): print(f"位置{idx1}错误,应为:{str1[idx1:]}") str1 = "abcdefg" str2 = "25abdfxx" print(f"字符串1:{str1}") print(f"字符串2:{str2}") compare_strings(str1, str2)