LeetCode--Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama" Output: true
Example 2:
Input: "race a car" Output: false
题目中是对数字和字母进行回文判断,而对其他的字符 ! ? . , " ; : @ # % $ * - / 等都是忽略的,所以有个问题,就是要忽略掉这些乱七八糟的东西,而一般的加条件进行判断也不太好用,
看到讨论区有 用Character.isLetterOrDigit(ch)来进行筛选,很厉害了。
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++){ if(Character.isLetterOrDigit(s.charAt(i))){ sb.append(s.charAt(i)); } } String str = sb.toString().toLowerCase(); String res = sb.reverse().toString().toLowerCase(); if(str.equals(res)) return true; return false; } }
那句话可以这样代替,很笨
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++){ if((s.charAt(i) >= 'a' && s.charAt(i) <= 'z') || (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') || (s.charAt(i) >= '0' && s.charAt(i) <= '9') ){ sb.append(s.charAt(i)); } } String str = sb.toString().toLowerCase(); String res = sb.reverse().toString().toLowerCase(); if(str.equals(res)) return true; return false; } }