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.
 
我的实现:
class Solution {
    public boolean isPalindrome(String s) {
        // P1:toLowerCase
        char[] cs = s.toLowerCase().toCharArray();
        int i = 0, j = cs.length - 1;
        while (i < j) {
            while (i < j && !isValid(cs[i])) i++;
            while (i < j && !isValid(cs[j])) j--;
            if (i < j && cs[i] != cs[j]) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
    
    private boolean isValid(char c) {
        return Character.isLetter(c) || Character.isDigit(c);
    }
}

 

九章实现:

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

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);
    }
}

 

posted @ 2018-08-05 07:23  jasminemzy  阅读(153)  评论(0编辑  收藏  举报