-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBuddyStrings.js
55 lines (46 loc) · 1.2 KB
/
BuddyStrings.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//Leetcode - Buddy Strings
/**
https://leetcode.com/problems/buddy-strings/
*/
/**
* @param {string} s
* @param {string} goal
* @return {boolean}
*/
var buddyStrings = function(s, goal) {
if(s.length < 2 || s.length !== goal.length){
return false;
}
if(s.length === 2){
return goal === s[1] + s[0];
}
let map = {};
let numberOfDifferentChars = 0;
let index1 = -1;
let index2 = -1;
for(let i = 0; i < s.length; i++){
if(s[i] !== goal[i]){
if(index1 === -1){
index1 = i;
}else{
index2 = i;
}
numberOfDifferentChars++;
if(numberOfDifferentChars > 2){
return false;
}
}
if(s[i] in map){
map[s[i]]++;
}else{
map[s[i]] = 1;
}
}
if(numberOfDifferentChars === 0 && Object.keys(map).length !== s.length){
return true;
}
if(numberOfDifferentChars === 2){
return goal === s.substring(0, index1) + s[index2] + s.substring(index1 + 1, index2) + s[index1] + s.substring(index2 + 1, s.length);
}
return false;
};