【字符串回文】Valid Palindrome

来源:互联网 发布:centos7 ubuntu 对比 编辑:程序博客网 时间:2024/05/23 16:54

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

解法:使用左右两个指针,若为合法字符则比较,否则前中间靠近

public class Solution {    public char fun(char c){        if(c >= 'a' && c <= 'z') return c;        if(c >= '0' && c <= '9') return c;        return '#';    }        public boolean isPalindrome(String s) {        if(s == null || s.length()==0) return true;                int len = s.length();        int left = 0;        int right = len - 1;        s = s.toLowerCase();        while(left < right){            char lc = '#';            while(left <= right){                lc = fun(s.charAt(left));                if(lc == '#') left++;                else break;            }                        char rc = '#';            while(left <= right){                rc = fun(s.charAt(right));                if(rc == '#') right--;                else break;            }                        if(lc == rc){                left++;                right--;            }            else return false;        }        return true;    }}


0 0