leetcode: 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.

原问题链接:https://leetcode.com/problems/valid-palindrome/

问题分析

  在这个问题里,因为要判断给定的字符串是否为回文。一开始就有几个初始条件需要判断。比如说如果s本身长度为0,应该返回true。

  而在实现里,我们还要考虑其他字符的情况。比如说不是给定的普通字符和数字,这些我们就应该跳过去。所以我们应该定义两个变量l, r。其中l = 0, r = s.length() - 1。分别表示字符串的两头。然后通过循环不断遍历和比较。如果碰到其中l, r同时为合法字符的情况下,但是两者不想等的话,就返回false。否则在循环结束后返回true。在比较两个字符的时候,我们要考虑到大小写的情况,需要将它们转换成同样的大写或者小写样式再来比较。

  详细的代码实现如下:

public class Solution {
    public boolean isPalindrome(String s) {
        if(s == null || s.isEmpty()) return true;
        int l = 0, r = s.length() - 1;
        while(l < r) {
            char lch = s.charAt(l), rch = s.charAt(r);
            if(!isValidChar(lch)) l++;
            else if(!isValidChar(rch)) r--;
            else if(Character.toLowerCase(lch) == Character.toLowerCase(rch)) {
                l++;
                r--;
            }
            else return false;
        }
        return true;
    }
    
    private boolean isValidChar(char c) {
        char ch = Character.toLowerCase(c);
        return Character.isLetterOrDigit(c);
    }
}

猜你喜欢

转载自shmilyaw-hotmail-com.iteye.com/blog/2308718