Problem
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
Note:
0 <= A.length <= 20000
0 <= B.length <= 20000
A
andB
consist only of lowercase letters.
Solution: HashTable
Time complexity: O(n)
Space complexity: O(26)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Author: Huahua // Running time: 7 ms class Solution { public: bool buddyStrings(string A, string B) { if (A.length() != B.length()) return false; vector<int> ca(26); vector<int> cb(26); int diff = 0; for (int i = 0; i < A.length(); ++i) { if (A[i] != B[i] && diff++ > 2) return false; ++ca[A[i]-'a']; ++cb[B[i]-'a']; } for (int i = 0; i < 26; ++i) { if (diff == 0 && ca[i] > 1) return true; if (ca[i] != cb[i]) return false; } return diff == 2; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment