码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 详解(valid plindrome)

时间:2016-04-19 10:05:51      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

Question: 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.
Example Questions Candidate Might Ask:
Q: What about an empty string? Is it a valid palindrome?
A: For the purpose of this problem, we define empty string as valid palindrome.
Solution:
O(n) runtime, O(1) space: The idea is simple, have two pointers – one at the head while the other one at the tail. Move them towards each other until they meet while skipping non-alphanumeric characters. Consider the case where given string contains only non-alphanumeric characters. This is a valid palindrome because the empty string is also a valid palindrome.        

public boolean isPalindrome(String s) {

  int i = 0, j = s.length() - 1;

  while (i < j) {

    while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;               //Character.asLetterOrDigit()  用来判断是不是字母或者数字
    while (i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
    if (Character.toLowerCase(s.charAt(i))!= Character.toLowerCase(s.charAt(j))) {    
      return false;

    }

    i++; j--;
  }
  return true;
}

注:这道题类似于用了两个指针在数组两头,同时,while (i < j && !Character.isLetterOrDigit(s.charAt(i))) i++ 用的很巧妙,避免了很多判断。

Leetcode 详解(valid plindrome)

标签:

原文地址:http://www.cnblogs.com/zehua-shu/p/5406940.html

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