Leetcode 25:验证回文串

Leetcode 25:验证回文串

题目描述

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

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

示例

示例 1:

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

示例 2:

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

思路

思路1:双指针

使用头尾指针进行匹配,如头尾指针指向的字符不同则判为错,注意边界处理即可

代码

思路1

class Solution {
    public boolean isPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return true;
        }
        s = s.toLowerCase();

        int low_index = 0;
        int high_index= s.length() - 1;
        boolean result = true;
        while (true) {
            while (high_index > low_index  && !isAlpha(s.charAt(low_index))) {
                low_index ++;
            }
            while (high_index > low_index && !isAlpha(s.charAt(high_index))) {
                high_index --;
            }
            if (high_index <= low_index) {
                break;
            }
            else if (high_index > low_index && isAlpha(s.charAt(low_index)) && isAlpha(s.charAt(high_index)) && s.charAt(high_index) != s.charAt(low_index)) {
                result = false;
                break;
            }
            else{
                high_index --;
                low_index++;
            }
        }
        return result;
    }

    private boolean isAlpha(char ch) {
        if ((ch >= '0' && ch <= '9') || (ch  >= 'a' && ch <= 'z')) {
            return true;
        } else{
            return false;
        }
    }
}

算法复杂度分析

思路1

时间复杂度

n

空间复杂度

1


文章作者: 小风雷
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小风雷 !
评论
 上一篇
Leetcode 131: 分割回文串 Leetcode 131: 分割回文串
Leetcode 131: 分割回文串题目描述给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。返回 s 所有可能的分割方案。 示例输入: "aab" 输出: [ ["aa",
2020-03-17
下一篇 
Leetcode 887:鸡蛋掉落 Leetcode 887:鸡蛋掉落
Leetcode 887:鸡蛋掉落题目描述你将获得 K 个鸡蛋,并可以使用一栋从 1 到 N  共有 N 层楼的建筑。 每个蛋的功能都是一样的,如果一个蛋碎了,你就不能再把它掉下去。 你知道存在楼层 F ,满足 0 <= F
2020-03-09
  目录