https://oj.leetcode.com/problems/valid-palindrome/
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.
Note:
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.
解题思路:
这题非常简单了。两个指针,一个从头,一个从结尾,往中间靠,直到他们相等。遇到非数字和字母的,不比较,跳过。遇到一个不相同的,就返回false。
要注意首先将整个字符串全变为大写或小写。其实,Character这个类有一个isLetterOrDigit(‘x’)的方法。
还要总结的是,||和&&在一起的时候,优先&&,然后||。
public class Solution { public boolean isPalindrome(String s) { if(s.length() == 0){ return true; }else{ s = s.toUpperCase(); int right = s.length() - 1; int left = 0; while(left < right){ if(!(s.charAt(left) >= 'A' && s.charAt(left) <= 'Z' || s.charAt(left) >= 'a' && s.charAt(left) <= 'z' || s.charAt(left) >= '0' && s.charAt(left) <= '9')){ left++; continue; } if(!(s.charAt(right) >= 'A' && s.charAt(right) <= 'Z' || s.charAt(right) >= 'a' && s.charAt(right) <= 'z' || s.charAt(right) >= '0' && s.charAt(right) <= '9')){ right--; continue; } if(s.charAt(left) != s.charAt(right)){ return false; } left++; right--; } return true; } } }