# 125. Valid Palindrome

{% embed url="<https://leetcode.com/problems/valid-palindrome/>" %}
Valid Palindrome
{% endembed %}

思路一：相向双指针

{% tabs %}
{% tab title="Python" %}

```python
class Solution:
    def isPalindrome(self, s: str) -> bool:
        i, j = 0, len(s)-1
        while i < j:
            left = s[i].lower()
            if not (left.isalpha() or left.isdigit()):
                i += 1
                continue
            else:
                right = s[j].lower()
                if not (right.isalpha() or right.isdigit()):
                    j -= 1
                    continue
                else:
                    if left != right:
                        return False
                    else:
                        i += 1
                        j -= 1
        return True
```

{% endtab %}

{% tab title="Java" %}

```python
class Solution {
    public boolean isPalindrome(String s) {
        int l = 0, r = s.length()-1;
        while (l < r) {
            if (!Character.isLetterOrDigit(s.charAt(l))) {
                l++;
                continue;
            }
            if (!Character.isLetterOrDigit(s.charAt(r))) {
                r--;
                continue;
            }
            if (Character.toLowerCase(s.charAt(l)) == Character.toLowerCase(s.charAt(r))) {
                l++;
                r--;
            } else {
                return false;
            }
        }
        return true;
    }
}
```

{% endtab %}
{% endtabs %}

思路二：粗暴点，去除无效字符后，全部小写，从中心切割，把右边逆序，再对比

{% tabs %}
{% tab title="Python" %}

```python
class Solution:
    def isPalindrome(self, s: str) -> bool:
        valid = [x.lower() for x in s if (x.isalpha() or x.isdigit())]
        mid = len(valid)//2
        left = valid[:mid]
        right = valid[len(valid)-mid:]
        right.reverse()
        if left == right:
            return True
        else:
            return False
```

{% endtab %}

{% tab title="Java" %}

```java
class Solution {
    public boolean isPalindrome(String s) {
        StringBuilder alnum = new StringBuilder();
        for (char c: s.toCharArray()) {
            if (Character.isLetterOrDigit(c)) {
                alnum.append(Character.toLowerCase(c));
            }
        }
        String left = alnum.substring(0, alnum.length()/2);
        String right = alnum.reverse().substring(0, alnum.length()/2);
        if (left.equals(right)) {
            return true;
        } else {
            return false;
        }
    }
}
```

{% endtab %}
{% endtabs %}
