描述
You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.
Example 1:
Input: s1 = "bank", s2 = "kanb"
Output: true
Explanation: For example, swap the first character with the last character of s2 to make "bank".
Example 2:
Input: s1 = "attack", s2 = "defend"
Output: false
Explanation: It is impossible to make them equal with one string swap.
Example 3:
Input: s1 = "kelb", s2 = "kelb"
Output: true
Explanation: The two strings are already equal, so no string swap operation is required.
Example 4:
Input: s1 = "abcd", s2 = "dcba"
Output: false
Note:
1 <= s1.length, s2.length <= 100
s1.length == s2.length
s1 and s2 consist of only lowercase English letters.
解析
根据题意,就是将 s1 和 s2 能够在最多交换任意两个字符后变一样,就返回 True ,否则返回 False 。思路简单,就是先判断两个字符串是否相等,相等直接返回 True ,否则再用计数器记录各自包含的字符的出现次数,如果不相等直接返回 False 。如果仍无法判断,则再遍历两个字符串,如果相同索引下的字符不相等次数大于等于 3 则返回 False ,否则为 True 。
解答
class Solution(object):
def areAlmostEqual(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
if s1 == s2:
return True
a = collections.Counter(s1)
b = collections.Counter(s2)
if a!=b:
return False
r = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
r += 1
return r < 3
运行结果
Runtime: 20 ms, faster than 52.90% of Python online submissions for Check if One String Swap Can Make Strings Equal.
Memory Usage: 13.5 MB, less than 59.65% of Python online submissions for Check if One String Swap Can Make Strings Equal.
原题链接:https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/
您的支持是我最大的动力