Description
You are given two strings s1 and s2, both of length n, consisting of lowercase English letters.
You can apply the following operation on any of the two strings any number of times:
- Choose any two indices
iandjsuch thati < jand the differencej - iis even, then swap the two characters at those indices in the string.
Return true if you can make the strings s1 and s2 equal, and false otherwise.
Example 1:
Input: s1 = "abcdba", s2 = "cabdab" Output: true Explanation: We can apply the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = "cbadba". - Choose the indices i = 2, j = 4. The resulting string is s1 = "cbbdaa". - Choose the indices i = 1, j = 5. The resulting string is s1 = "cabdab" = s2.
Example 2:
Input: s1 = "abe", s2 = "bea" Output: false Explanation: It is not possible to make the two strings equal.
Constraints:
n == s1.length == s2.length1 <= n <= 105s1ands2consist only of lowercase English letters.
Solutions
This function checks if two strings can be transformed into each other by only swapping characters within odd-indexed or even-indexed positions. It maintains two frequency-tracking arrays—one for characters at odd positions and one for even positions—then iterates through both strings simultaneously, incrementing the count for each character from s1 and decrementing for the corresponding character from s2 at each position. If both arrays end up with all zeros, it means s1 and s2 have identical character distributions at odd positions and identical distributions at even positions, making the strings compatible.
/**
* @param {string} s1
* @param {string} s2
* @return {boolean}
*/
var checkStrings = function(s1, s2) {
const n = s1.length;
const odd = new Array(26).fill(0);
const even = new Array(26).fill(0);
const aChar = 'a'.charCodeAt(0);
for (let i = 0; i < n; i++) {
if (i & 1) {
odd[s1.charCodeAt(i) - aChar]++;
odd[s2.charCodeAt(i) - aChar]--;
} else {
even[s1.charCodeAt(i) - aChar]++;
even[s2.charCodeAt(i) - aChar]--;
}
}
return odd.every(x => x === 0) && even.every(x => x === 0);
};