Skip to content

Commit f498c10

Browse files
committedMar 21, 2025
Add solution #859
1 parent 1b52d40 commit f498c10

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,7 @@
666666
856|[Score of Parentheses](./0856-score-of-parentheses.js)|Medium|
667667
857|[Minimum Cost to Hire K Workers](./0857-minimum-cost-to-hire-k-workers.js)|Hard|
668668
858|[Mirror Reflection](./0858-mirror-reflection.js)|Medium|
669+
859|[Buddy Strings](./0859-buddy-strings.js)|Easy|
669670
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
670671
868|[Binary Gap](./0868-binary-gap.js)|Easy|
671672
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|

‎solutions/0859-buddy-strings.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 859. Buddy Strings
3+
* https://leetcode.com/problems/buddy-strings/
4+
* Difficulty: Easy
5+
*
6+
* Given two strings s and goal, return true if you can swap two letters in s so the result is
7+
* equal to goal, otherwise, return false.
8+
*
9+
* Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and
10+
* swapping the characters at s[i] and s[j].
11+
*
12+
* For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
13+
*/
14+
15+
/**
16+
* @param {string} s
17+
* @param {string} goal
18+
* @return {boolean}
19+
*/
20+
var buddyStrings = function(s, goal) {
21+
if (s.length !== goal.length) return false;
22+
23+
const differences = [];
24+
const charCount = new Map();
25+
let hasDuplicate = false;
26+
27+
for (let i = 0; i < s.length; i++) {
28+
if (s[i] !== goal[i]) {
29+
differences.push(i);
30+
if (differences.length > 2) return false;
31+
}
32+
charCount.set(s[i], (charCount.get(s[i]) || 0) + 1);
33+
if (charCount.get(s[i]) > 1) hasDuplicate = true;
34+
}
35+
36+
if (differences.length === 0) return hasDuplicate;
37+
if (differences.length !== 2) return false;
38+
39+
const [first, second] = differences;
40+
return s[first] === goal[second] && s[second] === goal[first];
41+
};

0 commit comments

Comments
 (0)
Please sign in to comment.