字符串篇(python)——字符串数组中两个字符串的最小距离
程序员文章站
2024-02-27 23:13:15
...
题目描述
给定一个字符串数组strs,再给定两个字符串str1和str2,返回在strs中str1和str2的最小距离,如果str1或str2为null,或不在strs中,返回-1。
def findMinDistance(strs, str1, str2):
if str1 not in strs or str2 not in strs:
return -1
index_l1 = [i for i, j in enumerate(strs) if j == str1]
index_l2 = [i for i, j in enumerate(strs) if j == str2]
if len(index_l1) == 1 and len(index_l2) == 1:
return abs(index_l1[0] - index_l2[0])
else:
l = []
for i1 in index_l1:
for i2 in index_l2:
l.append(abs(int(i1) - int(i2)))
l.sort()
return l[0]
if __name__ == '__main__':
res = findMinDistance(["123", "1234", "111", "666", "we", "111"], "111", "we")
print(res)
下一篇: 凸包算法 Matlab实现