The question

Given a word, verify if it is a palindrome excluding spaces and punctuation.

The solution

This is the algorithm I came up to find out if a word is a palindrome:

– Place a pointer(left) on the first character

– Place a pointer(right) on the last character

– Check if the element at left is a character (not punctuation or space)

– If the element is not a character move the pointer one space to the right until you find a character

– Check if the element at right is a character

– If the element is not a character move the pointer one space to the left

– If left is greater than right return true

– Check if left and right elements are the same

– If they are not the same return false

– If they are the same move left one space to the right and right one space to the left

– Start over from step three

This would be the JavaScript implementation:

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
var palindrome = 'Anita lava la tina';
var palindrome2 = 'A man, a plan, a canal: Panama';
var notPalindrome = 'A man is not panama';

function isPalindrome(word) {
  function isCharacter(needle) {
    var haystack = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

    if (-1 !== haystack.indexOf(needle)) {
      return true;
    }

    return false;
  }

  var left = 0;
  var right = word.length - 1;

  while (left <= right) {
    while (!isCharacter(word[left])) {
      left++;
    }

    while(!isCharacter(word[right])) {
      right--;
    }

    if (word[left].toLowerCase() !== word[right].toLowerCase()) {
      return false;
    }

    left++;
    right--;
  }

  return true;
}

console.log(isPalindrome(palindrome)); // true
console.log(isPalindrome(palindrome2)); // true
console.log(isPalindrome(notPalindrome)); // false
[ application_design  computer_science  algorithms  javascript  programming  ]
Sorting algorithms computer_science algorithms javascript programming
Raft for reaching consensus computer_science algorithms
The Rabin-Karp algorithm computer_science algorithms javascript programming
Load testing a Rails app with Vegeta application_design programming
House painting problem computer_science algorithms javascript programming