Skip to content

Commit 03b7c6f

Browse files
NourBcitsvinayak
andauthored
Create palindrome algorithm (#134)
* Create palindrome algorithm * Update Palindrome.js Co-authored-by: vinayak <itssvinayak@gmail.com>
1 parent 94581a3 commit 03b7c6f

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

maths/Palindrome.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* A palindrome is any string that can be reversed and still be the same.
3+
* An example of one is 'radar', since it is spelled the same even after
4+
* being reversed. One method to check if a
5+
*
6+
* Here's how this works recursively:
7+
*
8+
* Palindrome('radar')
9+
* true && Palindrome('ada')
10+
* true && true && Palindrome('d')
11+
* true && true && true && true
12+
*
13+
* @flow
14+
* @complexity: O(n)
15+
*/
16+
17+
function PalindromeRecursive (string) {
18+
// Base case
19+
if (string.length < 2) return true
20+
21+
// Check outermost keys
22+
if (string[0] !== string[string.length - 1]) {
23+
return false
24+
}
25+
26+
return PalindromeRecursive(string.slice(1, string.length - 1))
27+
}
28+
29+
function PalindromeIterative (string) {
30+
const _string = string
31+
.toLowerCase()
32+
.replace(/ /g, '')
33+
.replace(/,/g, '')
34+
.replace(/'.'/g, '')
35+
.replace(/:/g, '')
36+
.split('')
37+
38+
// A word of only 1 character is already a palindrome, so we skip to check it
39+
while (_string.length > 1) {
40+
if (_string.shift() !== _string.pop()) {
41+
return false
42+
}
43+
}
44+
45+
return true
46+
}
47+
48+
// testing
49+
50+
console.log(PalindromeRecursive('Javascript Community'))
51+
console.log(PalindromeIterative('mom'))

0 commit comments

Comments
 (0)