[LeetCode] 125. Valid Palindrome Java
题目:
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.
题意及分析:给出一个字符串,只考虑其中的字母或者数字字符,问字符串是否是一个回文,注意空字符串也是回文。
方法一:先遍历一次字符串去除非数字字母字符,然后判断是否是回文,复杂度为n+n/2
class Solution { public boolean isPalindrome(String s) { if(s == null || s.length() == 0 ) return true; StringBuilder sb = new StringBuilder(); for(int i=0;i<s.length();i++){ //取出标点符号,只留下字母 char ch = s.charAt(i); if(Character.isLetterOrDigit(ch)){ sb.append(ch); } } //全部变为小写字母 String newStr = sb.toString().toLowerCase(); for(int i=0;i<newStr.length()/2;i++){ if(newStr.charAt(i)!=newStr.charAt(newStr.length()-1-i)) return false; } return true; } }
方法二:直接判断,每次分别从前和从后找到一个字母数字字符,若不相等直接返回false,复杂度最多为n
class Solution { public boolean isPalindrome(String s) { if(s == null || s.length() == 0 ) return true; int i = 0,j = s.length()-1; for(i=0,j=s.length()-1;i<j;++i,--j){ while(i<j && !Character.isLetterOrDigit(s.charAt(i))) i++; while(i<j && !Character.isLetterOrDigit(s.charAt(j))) j--; if(i<j && Character.toLowerCase(s.charAt(i))!=Character.toLowerCase(s.charAt(j))) return false; } return true; } }