Description
You are given two strings s1 and s2, both of length 4, 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 thatj - i = 2, 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 = "abcd", s2 = "cdab" Output: true Explanation: We can do the following operations on s1: - Choose the indices i = 0, j = 2. The resulting string is s1 = "cbad". - Choose the indices i = 1, j = 3. The resulting string is s1 = "cdab" = s2.
Example 2:
Input: s1 = "abcd", s2 = "dacb" Output: false Explanation: It is not possible to make the two strings equal.
Constraints:
s1.length == s2.length == 4s1ands2consist only of lowercase English letters.
Solutions
This function checks if two 4-character strings s1 and s2 can be considered equal under specific swapping rules. The logic verifies two conditions: for even positions (0 and 2), it returns true if either the characters match directly (s1[0] === s2[0] && s1[2] === s2[2]) OR they're swapped (s1[0] === s2[2] && s1[2] === s2[0]); similarly for odd positions (1 and 3), it allows either direct matches or swaps. The function returns true only if both conditions are satisfied, meaning the strings are equivalent under these position-swapping rules. Note: there is unreachable dead code after the return statement that attempts an alternative approach using Sets to collect characters at odd and even positions, which will never execute.
/**
* @param {string} s1
* @param {string} s2
* @return {boolean}
*/
var canBeEqual = function(s1, s2) {
return ((s1[0] === s2[0] && s1[2] === s2[2]) || (s1[0] === s2[2] && s1[2] === s2[0])) &&
((s1[1] === s2[1] && s1[3] === s2[3]) || (s1[1] === s2[3] && s1[3] === s2[1]));
const setOdd1 = new Set();
const setEven1 = new Set();
const setOdd2 = new Set();
const setEven2 = new Set();
for (let i = 0; i < 4; i++) {
if (i & 1) {
setOdd1.add(s1[i]);
setOdd2.add(s2[i]);
} else {
setEven1.add(s1[i]);
setEven2.add(s2[i]);
}
}
return setOdd1.size === setOdd2.size &&
[...setOdd1].every(char => setOdd2.has(char)) &&
setEven1.size === setEven2.size &&
[...setEven1].every(char => setEven2.has(char));
};