相对简单,就是从两边往中间推进,忽略其他字符。
public class Solution { public boolean isPalindrome(String s) { if (s.length() == 0) return true; int i = 0; int j = s.length() - 1; while (true) { while (i < s.length() && !isAlphaNum(s.charAt(i))) { i++; } while (j >= 0 && !isAlphaNum(s.charAt(j))) { j--; } if (i > j || i == s.length() || j < 0) break; int c1 = s.charAt(i); int c2 = s.charAt(j); if (c1 == c2 || c1-c2 == 'a'-'A' || c1-c2 == 'A' - 'a') { i++; j--; } else return false; } return true; } private boolean isAlphaNum(char c) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) return true; else return false; } }
这个参考答案写的很简洁,当然它修改了原来的字符串,不过这不是关键,也可以不改,关键是循环里的if-else写法:
bool isAlphanumeric(char &c) { if(c >= 'A' && c <= 'Z') c += 32; else if(c >= '0' && c <= '9' || c >= 'a' && c <= 'z') return true; else return false; return true; } bool isPalindrome(string s) { int i = 0, j = s.length()-1; while(i < j) { if(!isAlphanumeric(s[i])) ++i; else if(!isAlphanumeric(s[j])) --j; else if(s[i++] != s[j--]) return false; } return true; }
python3
class Solution: def isPalindrome(self, s: str) -> bool: if len(s) == 0 or len(s) == 1: return True i = 0 j = len(s) - 1 validChar = 'abcdefghijklmnopqrstuvwxyz0123456789' while True: while i < len(s) and s[i].lower() not in validChar: i += 1 while j >= 0 and s[j].lower() not in validChar: j -= 1 if i >= j: return True if s[i].lower() != s[j].lower(): return False i += 1 j -= 1