Created
February 5, 2025 18:52
-
-
Save tatsuyax25/adcaed2dacf619ac84a6496137cc0949 to your computer and use it in GitHub Desktop.
You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equa
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} s1 | |
* @param {string} s2 | |
* @return {boolean} | |
*/ | |
var areAlmostEqual = function(s1, s2) { | |
// Initialize an array to store the positions where s1 and s2 differ | |
let differences = []; | |
// Iterate through the strings to find differing positions | |
for (let i = 0; i < s1.length; i++) { | |
if (s1[i] !== s2[i]) { | |
differences.push(i); | |
} | |
} | |
// If there are no differing positions, the strings are already equal | |
if (differences.length === 0) { | |
return true; | |
} | |
// If there are exactly two differing positions, check if a single swap can make the strings equal | |
if (differences.length === 2) { | |
let [i, j] = differences; | |
return s1[i] === s2[j] && s1[j] === s2[i]; | |
} | |
// If there are more than two differing positions, it's not possible to make the strings equal with one swap | |
return false; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment