Skip to content

Commit 5501b98

Browse files
committedJan 5, 2025
Add solution #1657
1 parent 249da30 commit 5501b98

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,7 @@
333333
1566|[Detect Pattern of Length M Repeated K or More Times](./1566-detect-pattern-of-length-m-repeated-k-or-more-times.js)|Easy|
334334
1576|[Replace All ?'s to Avoid Consecutive Repeating Characters](./1576-replace-all-s-to-avoid-consecutive-repeating-characters.js)|Medium|
335335
1598|[Crawler Log Folder](./1598-crawler-log-folder.js)|Easy|
336+
1657|[Determine if Two Strings Are Close](./1657-determine-if-two-strings-are-close.js)|Medium|
336337
1668|[Maximum Repeating Substring](./1668-maximum-repeating-substring.js)|Easy|
337338
1669|[Merge In Between Linked Lists](./1669-merge-in-between-linked-lists.js)|Medium|
338339
1672|[Richest Customer Wealth](./1672-richest-customer-wealth.js)|Easy|
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* 1657. Determine if Two Strings Are Close
3+
* https://leetcode.com/problems/determine-if-two-strings-are-close/
4+
* Difficulty: Medium
5+
*
6+
* Two strings are considered close if you can attain one from the other using the following
7+
* operations:
8+
*
9+
* - Operation 1: Swap any two existing characters.
10+
* For example, abcde -> aecdb
11+
* - Operation 2: Transform every occurrence of one existing character into another existing
12+
* character, and do the same with the other character.
13+
* For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)
14+
*
15+
* You can use the operations on either string as many times as necessary.
16+
*
17+
* Given two strings, word1 and word2, return true if word1 and word2 are close, and false
18+
* otherwise.
19+
*/
20+
21+
/**
22+
* @param {string} word1
23+
* @param {string} word2
24+
* @return {boolean}
25+
*/
26+
var closeStrings = function(word1, word2) {
27+
const map1 = helper(word1);
28+
const map2 = helper(word2);
29+
30+
for (let i = 0; i < map1.length; i++) {
31+
if ((map1[i] === 0 || map2[i] === 0) && map1[i] !== map2[i]) {
32+
return false;
33+
}
34+
}
35+
36+
[map1, map2].forEach(m => m.sort((a, b) => b - a));
37+
38+
return map1.join('') === map2.join('');
39+
};
40+
41+
function helper(input) {
42+
const map = Array(26).fill(0);
43+
for (let i = 0; i < input.length; i++) {
44+
map[input.charCodeAt(i) - 'a'.charCodeAt(0)]++;
45+
}
46+
return map;
47+
}

0 commit comments

Comments
 (0)
Please sign in to comment.