Java Solution; O(n) running time, O(1) memory, 9ms.


  • 0
    S
    public class Solution {
      public boolean isPalindrome(String s) {
        if (s == null) return false;
    
        final int l = s.length();
        if (l < 2) return true;
    
        int i = 0;
        int j = l - 1;
    
        while (i <= j) {
          final char ic = Character.toLowerCase(s.charAt(i));
          final char jc = Character.toLowerCase(s.charAt(j));
          if (!Character.isLetterOrDigit(ic)) {
            i++;
          } else if (!Character.isLetterOrDigit(jc)) {
            j--;
          } else if (ic != jc) {
            return false;
          } else {
            i++;
            j--;
          }
        }
    
        return true;
      }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.