1. 题目
给定两个由小写字母构成的字符串 A 和 B ,只要我们可以通过交换 A 中的两个字母得到与 B 相等的结果,就返回 true ;否则返回 false 。
示例 1:
输入: A = "ab", B = "ba"
输出: true示例 2:
输入: A = "ab", B = "ab"
输出: false示例 3:
输入: A = "aa", B = "aa"
输出: true示例 4:
输入: A = "aaaaaaabc", B = "aaaaaaacb"
输出: true示例 5:
输入: A = "", B = "aa"
输出: false提示:
0 <= A.length <= 20000
0 <= B.length <= 20000
A 和 B 仅由小写字母构成。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/buddy-strings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
class Solution {
public:bool buddyStrings(string A, string B) {if(A.size() < 2 || B.size() < 2 || A.size() != B.size())return false;int countA[26] = {0}, countB[26] = {0}, diff = 0;for(int i = 0; i < A.size(); ++i){if(A[i] != B[i])diff++;countA[A[i]-'a']++;countB[B[i]-'a']++;}for(int i = 0; i < 26; ++i)if(countA[i] != countB[i])return false;//个数不一样。不行bool hasSameChar = false;for(int i = 0; i < 26; ++i)if(countA[i] >= 2){hasSameChar = true;//有相同的字符break;}if(diff == 2 || (diff == 0 && hasSameChar))return true;//不同的位置为2,或者全部一样,有相同字符可以互换return false;}
};
4 ms 9.1 MB