Valid Palindrome

来源:互联网 发布:sql语句排序查询 编辑:程序博客网 时间:2024/05/05 00:37

https://oj.leetcode.com/problems/valid-palindrome/

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 boolean isPalindrome(String s)


本题算法如下:

这题其实很简单,就是头尾指针往中间扫,跳过所有非法字符(不是a~z之间的字符均非法),匹配头尾指针的内容即可。

    public boolean isPalindrome(String s) {        int head = 0, tail = s.length() - 1;        s = s.toLowerCase();        while(head < tail){            while((s.charAt(head) > 'z' || s.charAt(head) < 'a') && (s.charAt(head) > '9' || s.charAt(head) < '0') && head < tail)                head++;            while(s.charAt(tail) > 'z' || s.charAt(tail) < 'a' && (s.charAt(tail) > '9' || s.charAt(tail) < '0')&& head < tail)                tail--;            if(s.charAt(head) != s.charAt(tail))                return false;            head++;            tail--;        }        return true;    }


0 0
原创粉丝点击