码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-12-03 13:26:38      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

原题链接在这里:https://leetcode.com/problems/valid-palindrome/

注意在用Character.isLetter(s.charAt(i)) 或者 Character.isDigit(s.charAt(i))前需检验 i 是否index out of bound 了。

Time Complexity: O(n), n = s.length(). Space: O(1).

AC Java:

public class Solution {
    public boolean isPalindrome(String s) {
        if(s == null || s.length() == 0){
            return true;
        }
        s = s.trim().toLowerCase();
        int l = 0;
        int r = s.length()-1;
        while(l < r){
            while(l <= s.length()-1 && !Character.isLetter(s.charAt(l)) && !Character.isDigit(s.charAt(l))){
                l++;
            }
            while(r >= 0 && !Character.isLetter(s.charAt(r)) && !Character.isDigit(s.charAt(r))){
                r--;
            }
            if(l <= s.length()-1 && r >= 0 && s.charAt(l) != s.charAt(r)){
                return false;
            }
            l++;
            r--;
        }
        return true;
    }
}

 

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

标签:

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5015593.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!