Loading

Medium | LeetCode 125. 验证回文串 | 双指针

125. 验证回文串

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

输入: "A man, a plan, a canal: Panama"
输出: true

示例 2:

输入: "race a car"
输出: false

解题思路

方法一: 字符串反转

public boolean isPalindrome(String s) {
    StringBuffer sgood = new StringBuffer();
    int length = s.length();
    for (int i = 0; i < length; i++) {
        char ch = s.charAt(i);
        if (Character.isLetterOrDigit(ch)) {
            // 把多余字符过滤, 并且将字符转为小写字符
            sgood.append(Character.toLowerCase(ch));
        }
    }
    // 字符串反转
    StringBuffer sgood_rev = new StringBuffer(sgood).reverse();
    // 比较反转后的字符串是否相等
    return sgood.toString().equals(sgood_rev.toString());
}

方法二: 双指针

public boolean isPalindrome(String s) {
    StringBuffer sgood = new StringBuffer();
    int length = s.length();
    // 把多余字符过滤, 并且将字符转为小写字符
    for (int i = 0; i < length; i++) {
        char ch = s.charAt(i);
        if (Character.isLetterOrDigit(ch)) {
            sgood.append(Character.toLowerCase(ch));
        }
    }
    int n = sgood.length();
    int left = 0, right = n - 1;
    // 双指针判断
    while (left < right) {
        if (Character.toLowerCase(sgood.charAt(left)) != Character.toLowerCase(sgood.charAt(right))) {
            return false;
        }
        ++left;
        --right;
    }
    return true;
}

当然可以不过滤非字母和数字字符, 直接判断。代码如下

public boolean isPalindrome(String s) {
    int n = s.length();
    int left = 0, right = n - 1;
    while (left < right) {
        while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
            ++left;
        }
        while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
            --right;
        }
        if (left < right) {
            if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
                return false;
            }
            ++left;
            --right;
        }
    }
    return true;
}
posted @ 2021-02-27 20:36  反身而诚、  阅读(57)  评论(0编辑  收藏  举报