Leetcode题解之字符串(5) 验证回文字符串

题目:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/5/strings/36/

题目描述 :

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

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

示例 1:

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

示例 2:

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

思路:先把字母都转换为小写,然后用双指针,一个从开头开始,一个从结尾开始。遇到不符合条件的字符,自加1(开头指针) 或者自减1(结尾指针)。然后再判断两个指针对应的值是否相等。两种方法思路一样。第二种比较节省内存还有比较规范吧。

class Solution {
  public boolean isPalindrome(String s) {

    s = s.toLowerCase();

    int startIndex = 0;
    int endIndex = s.length() - 1;
    while (startIndex < endIndex && startIndex < s.length() - 1) {
        char pre = s.charAt(startIndex);
        char aft = s.charAt(endIndex);
        if (!((pre >= 'a' && pre <= 'z') || (pre >= '0' && pre <= '9'))) {
            startIndex++;
            continue;
        }
        if (!((aft >= 'a' && aft <= 'z') || (aft >= '0' && aft <= '9'))) {
            endIndex--;
            continue;
        }

        if (pre != aft) {
            return false;
        }
        startIndex++;
        endIndex--;
    }

    return true;
}

}



class Solution {
    public boolean isPalindrome(String s) {
	    int left = 0;
        int right = s.length() - 1;
        while(left < right){
            if(!isAlphaNum(s.charAt(left))){
                left ++;
            }else if(!isAlphaNum(s.charAt(right))){
                right --;
            }else if((s.charAt(left) + 32 - 'a') % 32 != (s.charAt(right) + 32 - 'a') % 32){
                return false;
            }else{
                left ++;
                right --;
            }
        }
        return true;
    }
    private boolean isAlphaNum(char c){
        if(c >= 'a' && c <= 'z') return true;
        if(c >= 'A' && c <= 'Z') return true;
        if(c >= '0' && c <= '9') return true;
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34433210/article/details/84034908
今日推荐