iluwatar/30-seconds-of-java

O(1) space palindrome check

AddeusExMachina opened this issue · 0 comments

The current palindrome check snippet uses O(n) space, it can be improved to use O(1) space with this simple algorithm:

  public static boolean isPalindrome(String s) {
    for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
      while (i < j && !Character.isLetter(s.charAt(i))) {
        i++;
      }
      while (i < j && !Character.isLetter(s.charAt(j))) {
        j--;
      }

      if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {
        return false;
      }
    }

    return true;
  }