LintCode Valid Palindrome

准备开始刷题,然后希望把做过的题写在这里,这样既能加深印象,又能有机会找出自己潜在的问题。
题目如下:

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Notice
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.

解题代码如下:
思路很简单,就是设置两个指针,一个头一个尾,一直对比到中间,如果遇到不一样就return false。
当然,题目还要求忽略空格和数字,所以这题需要用到Character对象的方法, 这个时间久远不用可能会忘,所以需要认真看一下。

public class Solution {
/**
* @param s A string
* @return Whether the string is a valid palindrome
*/
public boolean isPalindrome(String s) {
          // Write your code here
          if( s.length() == 0){
          return true;
          }
          int left = 0;
          int right = s.length()-1;
          while(left < right){
                    if(!Character.isLetter(s.charAt(left)) && !Character.isDigit(s.charAt(left))){
                              left++;
                              continue;
                    }
                    if(!Character.isLetter(s.charAt(right)) && !Character.isDigit(s.charAt(right))){
                              right--;
                              continue;
                    }
                    if(Character.toUpperCase(s.charAt(left++)) != Character.toUpperCase(s.charAt(right--))){
                              return false;
                    }
          }
          return true;
          }
}

你可能感兴趣的:(LintCode Valid Palindrome)