Skip to content

Commit 8525090

Browse files
authored
Create 859-buddy-strings.js
1 parent 4fb4d3c commit 8525090

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

859-buddy-strings.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {string} A
3+
* @param {string} B
4+
* @return {boolean}
5+
*/
6+
const buddyStrings = function(A, B) {
7+
if(A.length !== B.length) return false
8+
const aCode = ('a').charCodeAt(0)
9+
if(A === B) {
10+
const count = new Array(26).fill(0)
11+
for(let i = 0; i < A.length; i++) {
12+
count[A.charCodeAt(i) - aCode]++
13+
}
14+
for(let el of count) {
15+
if(el > 1) return true
16+
}
17+
return false
18+
} else {
19+
const arr = []
20+
for(let i = 0; i < A.length; i++) {
21+
if(A[i] !== B[i]) {
22+
arr.push(i)
23+
if(arr.length > 2) return false
24+
}
25+
}
26+
if(arr.length !== 2) return false
27+
return A[arr[0]] === B[arr[1]] && A[arr[1]] === B[arr[0]]
28+
}
29+
};

0 commit comments

Comments
 (0)