File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 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' ) )
You can’t perform that action at this time.
0 commit comments