-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathisApproxPalindrome.js
64 lines (53 loc) · 1.36 KB
/
isApproxPalindrome.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
55
56
57
58
59
60
61
62
63
64
// Determine if a string of length S is a palindrome if you remove at most a single characters from that string.
//Best Case: O(1) & Worst Case: O(2N)
const isPalindromeIfNLettersAreRemoved = (
str,
maxNumbersOfLetters = 1,
lettersRemoved = 0
) => {
if (str.length === 0) {
return true;
}
let result = isPalindrome(str);
if (result.isPalindrome) {
return true;
}
if (lettersRemoved >= maxNumbersOfLetters) {
return false;
}
const { badIndex } = result;
str = str.slice(0, badIndex) + str.slice(badIndex + 1);
lettersRemoved++;
return isPalindromeIfNLettersAreRemoved(
str,
maxNumbersOfLetters,
lettersRemoved
);
};
// O(1) Space & O(N) time
const isPalindrome = str => {
const strArr = str.split("");
const strLength = strArr.length;
const halfLength = Math.ceil(strArr.length / 2);
let result = {
isPalindrome: true,
badIndex: null
};
strArr.forEach((char, idx) => {
const correspondingChar = strArr[strLength - 1 - idx];
if (char !== correspondingChar) {
result = {
isPalindrome: false,
badIndex: idx
};
}
});
return result;
};
const data = ["abca", "aba", "abcd", "acba", "", "racecafr"]; // true, true, false, true, true, true
data.forEach(testCase => {
console.log(
`isApproxPalindrome($(testCase))`,
isPalindromeIfNLettersAreRemoved(testCase)
);
});