Determining whether the string is palindromic sequence

 Determining whether the string is palindromic sequence

topic:

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

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

示例 1:

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

示例 2:

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

 

Ideas:

String lowercase string from both ends of the string start and end character is determined whether or not the starting of filtration are not equal, if not equal returns false, if they are equal then continues to determine left ++ right--
 

Letters or numbers is not found then removed leaving an index ++, if the right and left empathy index characters filtered.
 

public static boolean isPalindrome2(String s) {
    if(s.equals("") || s == null) {
        return true;
    }
    //将字符串转为小写
    s = s.toLowerCase();

    int left = 0;
    int right = s.length() - 1;
    while(left < right) {
        //过滤字符
        if((s.charAt(left) >='a' && s.charAt(left) <= 'z' ||
                s.charAt(left) >= '0' && s.charAt(left) <= '9')
                &&
                (s.charAt(right) >='a' && s.charAt(right) <= 'z' ||
                        s.charAt(right) >= '0' && s.charAt(right) <= '9')
        ) {
            if(s.charAt(left) != (s.charAt(right))){
                return false;
            }else {
                left ++;
                right --;
            }
        //判断left索引处值是否不为字母或字符,如果是则left++,否则right--
        } else if (
                s.charAt(left) > 'z' || s.charAt(left) < '0'
                || s.charAt(left) > '9' && s.charAt(left) < 'a') {
            left ++;
        } else {
            right --;
        }

    }
    return true;
}

 

Published 70 original articles · won praise 18 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_40325734/article/details/84996989