Determine if Two Strings Are Close
MediumHash TableStringSortingCounting
Solution
export function closeStrings(word1: string, word2: string): boolean {
if (word1.length !== word2.length) {
return false;
}
const set1 = Array.from(new Set(word1)).sort();
const set2 = Array.from(new Set(word2)).sort();
if (!shallowCompare(set1, set2)) {
return false;
}
const counter1 = new Map<string, number>();
const counter2 = new Map<string, number>();
for (let i = 0; i < word1.length; i++) {
counter1.set(word1[i], (counter1.get(word1[i]) || 0) + 1);
counter2.set(word2[i], (counter2.get(word2[i]) || 0) + 1);
}
const count1 = Array.from(counter1.values()).sort((a, b) => a - b);
const count2 = Array.from(counter2.values()).sort((a, b) => a - b);
return shallowCompare(count1, count2);
}
function shallowCompare<T>(arr1: Array<T>, arr2: Array<T>) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}