题解 | 字符串距离计算
字符串距离计算
https://www.nowcoder.com/practice/82bd533cd9c34df29ba15bbf1591bedf
"""
解题思路:
1.输入参数,字符串S1,S2 ,
校验:
-字符串长度相等
-字符串长度范围 1<=len(s1)<=5e4
-S1,S2 均为小写字母
2.创建一个数组【a-z】lettersLow
import string
letters = list(string.ascii_lowercase)
3.遍历小写字母lettersLow,取一个字母X1;再遍历lettersLow,取一个字母X2
for char in s1:
将S1中的所有字母X1均替换成X2后,比较s1和s2每个位置是否相等,如果不相等 ,数字num 加一。
将这些数字存放到列表中listNum.
4.返回listNum中的最小值。
"""
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 计算最少的距离
# @param S1 string字符串 第一个字符串
# @param S2 string字符串 第二个字符串
# @return int整型
#
class Solution:
def GetMinDistance(self , s1 , s2 ):
# write code here
list_num=[]
if len(s1)!=len(s2):
return None
if len(s1)>5e4 or len(s1)<1 :
return None
if not s1.islower():
return None
import string
letters_low =list(string.ascii_lowercase)
for x1 in letters_low:
for x2 in letters_low:
s1_copy=s1
s1_copy=s1_copy.replace(x1,x2)
num = 0
for i in range(len(s1)):
if s1_copy[i]!=s2[i]:
num+=1
list_num.append(num)
return min(list_num)