Given two strings s
and goal
, return true
if you can swap two letters in s
so the result is equal to goal
, otherwise, return false
.
Swapping letters is defined as taking two indices i
and j
(0-indexed) such that i != j
and swapping the characters at s[i]
and s[j]
.
0
and 2
in "abcd"
results in "cbad"
.Example 1:
Input: s = "ab", goal = "ba"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
Example 2:
Input: s = "ab", goal = "ab"
Output: false
Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
Example 3:
Input: s = "aa", goal = "aa"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
Constraints:
s.length
, goal.length
<= 2 * 104s
and goal
consist of lowercase letters.
function buddyStrings(s, goal) {
if (s.length !== goal.length) return false;
const different = [];
for (let i = 0; i < s.length; i++) {
if (s[i] !== goal[i]) {
different.push(i);
}
}
if (different.length === 2) {
const [a, b] = different;
if (s[a] === goal[b] && s[b] === goal[a]) return true;
}
// 全都一樣的情況
if (different.length === 0) {
const map = [];
for (let i = 0; i < s.length; i++) {
if (map[s[i]]) return true;
map[s[i]] = true;
}
}
return false;
}
Marsgoat Dec 2, 2022
function buddyStrings(s: string, goal: string): boolean {
if (s.length !== goal.length) return false;
const hash = new Map<string, number>();
s.split('').forEach((char) => hash.set(char, (hash.get(char) ?? 0) + 1));
if (s === goal) {
for (const value of hash.values()) {
if (value !== 1) {
return true;
}
}
return false;
}
let swapCount = 0;
goal.split('').forEach((char, i) => {
if (char !== s[i]) {
if (swapCount >= 2) return false;
swapCount++;
}
const value = hash.get(char);
if (value) {
const newValue = value - 1;
newValue ? hash.set(char, newValue) : hash.delete(char);
}
});
return hash.size === 0;
}
Sheep July 3, 2023