Lintcode415 - Valid Palindrome - easy

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Example
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Challenge
O(n) time without extra memory.
 
双指针往中间走,没有被不相等中断从而最后实现指针交叉就是回文串。遇到特殊字符用while跳过缩进,缩进过程中确认没有超过边界。
细节:
1. 要询问面试官空字符串”"算不算回文串。此题算是。
2.记得根据题目要求做不区分大小写。
3.实用方法:Character.isLetter(char c), Character.isDigit(char c), Character.toLowerCase(char c). (返回char)。library名不带s。
4.对比char是否相等用==,对比Character是否相等用equals.
 
我的实现:
public class Solution {
    /**
     * @param s: A string
     * @return: Whether the string is a valid palindrome
     */
    public boolean isPalindrome(String s) {
        //!! 忽略大小写!!审题。
        
        if (s == null) {
            return false;
        }
        int head = 0;
        int tail = s.length() - 1;
        
        while (head < tail) {
            while (!isValid(s.charAt(head)) && head < tail) {
                head++;
            }
            while (!isValid(s.charAt(tail)) && head < tail) {
                tail--;
            }
            if (isEqual(s.charAt(head), s.charAt(tail))) {
                head++;
                tail--;
            } else {
                break;
            }
        }
        return head >= tail;
    }
    
    private boolean isValid(Character c) {
        return Character.isLetter(c) || Character.isDigit(c);
    }
    
    private boolean isEqual(char a, char b) {
        // Character.toLowerCase方法以及它返回的是char
        return Character.toLowerCase(a) == Character.toLowerCase(b);
    }
}

九章实现:

他们在滑过无效字符的时候就允许交叉,比较宽松,可以一直滑到最后。

public class Solution {
    public boolean isPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return true;
        }

        int front = 0;
        int end = s.length() - 1;
        while (front < end) {
            while (front < s.length() - 1&& !isvalid(s.charAt(front))){ // nead to check range of a/b
                front++;
            }

            while (end > 0 && ! isvalid(s.charAt(end))) { // same here, need to check border of a,b
                end--;
            }

            if (Character.toLowerCase(s.charAt(front)) != Character.toLowerCase(s.charAt(end))) {
                break;
            } else {
                front++;
                end--;
            }
        }

        return end <= front; 
    }

    private boolean isvalid (char c) {
        return Character.isLetter(c) || Character.isDigit(c);
    }
}

猜你喜欢

转载自www.cnblogs.com/jasminemzy/p/9420879.html