-
Notifications
You must be signed in to change notification settings - Fork 0
/
680. Valid Palindrome II.js
72 lines (54 loc) · 1.22 KB
/
680. Valid Palindrome II.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
65
66
67
68
69
70
71
72
/*
Given a string s, return true if the s can be palindrome after deleting at most one character from it.
Example 1:
Input: s = "aba"
Output: true
Example 2:
Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.
Example 3:
Input: s = "abc"
Output: false
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
*/
/**
* @param {string} s
* @return {boolean}
*/
var validPalindrome = function(s) {
const isPalindrome = t => {
let l = 0, r = t.length - 1;
if (t.length === 0 || t.length === 1) { return true; }
while (l < r && t[l] === t[r]) {
l++;
r--;
}
return t[l] === t[r];
}
// immediate check
if (isPalindrome(s)) { return true; }
let leftChars = '';
let rightChars= '';
// inspect missmatch char
for (let l = 0, r = s.length - 1; l <= r;) {
// left & right are equal
if (s[l] === s[r]) {
leftChars += s[l];
rightChars = s[r] + rightChars;
l++;
r--;
continue;
}
if (isPalindrome(leftChars + s.slice(l, r) + rightChars)) {
return true;
}
if (isPalindrome(leftChars + s.slice(l + 1, r + 1) + rightChars)) {
return true;
}
return false;
}
return true;
};