给你长度相等的两个字符串 s1 和 s2 。一次 字符串交换 操作的步骤如下:选出某个字符串中的两个下标(不必不同),并交换这两个下标所对应的字符。
如果对 其中一个字符串 执行 最多一次字符串交换 就可以使两个字符串相等,返回 true ;否则,返回 false 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/check-if-one-string-swap-can-make-strings-equal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:首先哈希表得相同,其次只能有两个字符位置不同
python3实现:
class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
# 哈希表确定两个字符串元素相同,且只有两个字符串位置不同,才返回true
dic_s1 = collections.Counter(s1)
dic_s2 = collections.Counter(s2)
if dic_s1 == dic_s2:
count = 0
p = 0
while p <= len(s1) - 1:
if s1[p] != s2[p]:
count += 1
p += 1
if count > 2:
return False
if count <= 2:
return True
else:
return False

优化一下,直接用指针
class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
count = 0
p = 0
idx = []
while p <= len(s1) - 1:
if s1[p] != s2[p]:
count += 1
if s1[p] not in s2:
return False
if s1[p] not in idx:
idx.append(s1[p])
if s2[p] not in idx:
idx.append(s2[p])
if count > 2:
return False
p += 1
if count == 0:
return True
if count == 2 and len(idx) == 2:
return True
return False

溜了溜了!