Valid Palindrome

来源:互联网 发布:软件开发包 编辑:程序博客网 时间:2024/04/30 08:21

题目地址:https://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.

题目本身不是很复杂,与其他判断回文字符串的逻辑是类似的,本题目需要注意两个地方:

  1. 只比较字母和数字,其他字符一律略过;
  2. 字母大小写不分,也就是说A和a可以认为是一样的,所以我们会用偏移为32这样的方法来判断,即Math.abs('A' - 'a') = 32,但是注意这里可能有坑,那就是偏移量为32的两个字符必须限定是两个字母相比较,因为Math.abs('0' - 'P') = 32,但是很显然P与p才是相对应的字符,跟0根本没啥关系,所以要注意到这一点;

以上两点注意到了,也就没啥其他问题了,代码实现如下:

public class ValidPalindrome {    public static boolean isPalindrome(String s) {        if (s.length() == 0)            return true;        if (s.length() == 1)            return true;        int i = 0;        int j = s.length() - 1;        while (i < j) {            if (!Character.isLetterOrDigit(s.charAt(i))) {                i++;                continue;            }            if (!Character.isLetterOrDigit(s.charAt(j))) {                j--;                continue;            }            if (s.charAt(i) == s.charAt(j) ||                    (Character.isLetter(s.charAt(i)) &&                            Character.isLetter(s.charAt(j)) &&                            Math.abs(s.charAt(i) - s.charAt(j)) == 32)) {                i++;                j--;                continue;            } else {                return false;            }        }        return true;    }    public static void main(String[] args) {        System.out.println(isPalindrome("0P"));    }}

以上实现时间复杂度为:O(n)。

0 0
原创粉丝点击