iluwatar / 30-seconds-of-java

Collection of reusable tested Java 17 compatible code snippets that you can understand in 30 seconds or less.
https://java-design-patterns.com/snippets.html
MIT License
1.04k stars 410 forks source link

O(1) space palindrome check #169

Closed AddeusExMachina closed 1 year ago

AddeusExMachina commented 1 year ago

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;
  }