File tree 2 files changed +42
-0
lines changed
2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change 666
666
856|[ Score of Parentheses] ( ./0856-score-of-parentheses.js ) |Medium|
667
667
857|[ Minimum Cost to Hire K Workers] ( ./0857-minimum-cost-to-hire-k-workers.js ) |Hard|
668
668
858|[ Mirror Reflection] ( ./0858-mirror-reflection.js ) |Medium|
669
+ 859|[ Buddy Strings] ( ./0859-buddy-strings.js ) |Easy|
669
670
867|[ Transpose Matrix] ( ./0867-transpose-matrix.js ) |Easy|
670
671
868|[ Binary Gap] ( ./0868-binary-gap.js ) |Easy|
671
672
872|[ Leaf-Similar Trees] ( ./0872-leaf-similar-trees.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments