-
Notifications
You must be signed in to change notification settings - Fork 0
/
valid-palindromeII.js
71 lines (60 loc) · 1.71 KB
/
valid-palindromeII.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
//Given a string s, return true if the s can be palindrome after deleting at most one character from it.
function validPalindrome(s) {
let alphanumericStr = '';
for (let char of s) {
if (
(char >= 'a' && char <= 'z') ||
(char >= 'A' && char <= 'Z') ||
(char >= '0' && char <= '9')
) {
alphanumericStr += char.toLowerCase();
}
}
function isPalindromeRange(s, left, right) {
while (left < right) {
if (s[left] !== s[right]) {
return false;
}
left++;
right--;
}
return true;
}
let i = 0;
let j = alphanumericStr.length - 1;
while (i < j) {
if (alphanumericStr[i] !== alphanumericStr[j]) {
return (
isPalindromeRange(alphanumericStr, i + 1, j) ||
isPalindromeRange(alphanumericStr, i, j - 1)
);
}
i++;
j--;
}
return true;
}
//optimized
function isPalindrome(s) {
const isAlphanumeric = (c) => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
const str = s.toLowerCase();
let i = 0, j = str.length - 1;
while (i < j) {
while (i < j && !isAlphanumeric(str[i])) i++;
while (i < j && !isAlphanumeric(str[j])) j--;
if (str[i] !== str[j]) {
const skipLeft = checkRange(str, i + 1, j);
const skipRight = checkRange(str, i, j - 1);
return skipLeft || skipRight;
}
i++;
j--;
}
return true;
}
function checkRange(s, left, right) {
while (left < right) {
if (s[left++] !== s[right--]) return false;
}
return true;
}