10. Buddy Strings

Buddy Stringsarrow-up-right

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

這題目不難,但要仔細分析所有狀況

- If the lengths differ, return False. - If the strings are the same with duplicate characters, return True. - Count the number of different characters. If the count is not 2, return False. - If the characters are equal to each other swapped, then return True. <-- 可以正確被swap

Last updated