鱼C论坛

 找回密码
 立即注册
查看: 4839|回复: 3

[已解决]字符串

[复制链接]
发表于 2023-4-29 11:34:13 | 显示全部楼层    本楼为最佳答案   
  1. def is_one_char_diff(str1, str2):
  2.     if len(str1) == len(str2):
  3.         count_diff = 0
  4.         for i in range(len(str1)):
  5.             if str1[i] != str2[i]:
  6.                 count_diff += 1
  7.             if count_diff > 1:
  8.                 return False
  9.         return count_diff == 1
  10.     elif abs(len(str1) - len(str2)) == 1:
  11.         if len(str1) > len(str2):
  12.             str1, str2 = str2, str1
  13.         i = j = 0
  14.         while i < len(str1) and j < len(str2):
  15.             if str1[i] != str2[j]:
  16.                 j += 1
  17.                 if j - i > 1:
  18.                     return False
  19.             else:
  20.                 i += 1
  21.                 j += 1
  22.         return True
  23.     else:
  24.         return False
复制代码

这个函数可以判断两个字符串是否只有一个字符的差别。首先判断两个字符串长度是否相等,如果相等,则统计不同的字符数,如果不同的字符数为1,则返回True;否则返回False。如果两个字符串长度相差1,则将较短的字符串作为str1,从左到右遍历两个字符串,遇到不同的字符则将较长字符串的指针j后移一位,如果j和i之间的距离大于1,则返回False;否则继续遍历,直到遍历完较短的字符串,如果都没有返回False,则返回True。如果两个字符串长度差别大于1,则直接返回False。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-4-1 19:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表