-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalindrome-index.js
More file actions
81 lines (63 loc) · 1.91 KB
/
palindrome-index.js
File metadata and controls
81 lines (63 loc) · 1.91 KB
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
73
74
75
76
77
78
79
80
81
function palindromeIndex (s) {
for (let i = 0; i < s.length / 2; i++) {
if (s[i] !== s[s.length - 1 - i]) {
const stringA = s.slice(0, i).concat(s.slice(i + 1));
const stringB = s
.slice(0, s.length - 1 - i)
.concat(s.slice(s.length - i));
if (checkPal(stringA)) return i;
if (checkPal(stringB)) return s.length - 1 - i;
return -1;
}
}
return -1;
function checkPal (string) {
if(string.slice(0, Math.floor(string.length / 2)) ===
string
.slice(Math.ceil(string.length / 2))
.split('')
.reverse()
.join('')) return true
}
}
//solution
// const checkPal = string =>
// string.slice(0, Math.floor(string.length / 2)) ===
// string
// .slice(Math.ceil(string.length / 2))
// .split('')
// .reverse()
// .join('');
// for (let i = 0; i < s.length / 2; i++) {
// if (s[i] !== s[s.length - 1 - i]) {
// const stringA = s.slice(0, i).concat(s.slice(i + 1));
// const stringB = s
// .slice(0, s.length - 1 - i)
// .concat(s.slice(s.length - i));
// if (checkPal(stringA)) return i;
// if (checkPal(stringB)) return s.length - 1 - i;
// return -1;
// }
// }
// return -1;
//1. basecase: middle character. if the str.length is less than 1, return true.
//2. define first character
//3. define the last character
//4. compare the first and the last
//5. if it's true, return true then write recursive line
//6. if it's false, return false
const isPalindrome = (originalStr) => {
let str = originalStr.toUpperCase();
if(str.length <= 1){
return true
}
let first = str.slice(0, 1)
let last = str.slice(-1)
console.log('first', first)
console.log('last', last)
if(first === last){
return isPalindrome(str.slice(1,-1))
}else{
return false
}
}