859. Buddy Strings
Easy
273160FavoriteShare
Given two strings A
and B
of lowercase letters, return true
if and only if we can swap two letters in A
so that the result equals B
.
Example 1:
Input: A = "ab", B = "ba" Output: true
Example 2:
Input: A = "ab", B = "ab" Output: false
Example 3:
Input: A = "aa", B = "aa" Output: true
Example 4:
Input: A = "aaaaaaabc", B = "aaaaaaacb" Output: true
Example 5:
Input: A = "", B = "aa" Output: false
注意:如果A和B不一样的地方不是2处,那么肯定返回false。如果A和B是一样的,那么久判断A是否有两个一样的字母,因为这两个一样的字母swap后得到的字符串与swap前得到的是一样的。如果A和B不一样的地方是2处,那么记录一下这2处的下标,swap一下,看一看swap前后是否一致。具体思路就是这样。时间复杂度为O(n),空间复杂度为O(n)