題目:python
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.git
For example,"A man, a plan, a canal: Panama"
is a palindrome."race a car"
is not a palindrome.ide
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.oop
連接: http://leetcode.com/problems/valid-palindrome/this
一刷,用兩個指針從兩個方向,出現的問題spa
1. string methods掌握不熟,str.isalpha(), str.isdigit(), str.isalnum()指針
2. 內部兩個while loop以後須要再檢查index是否valid,不然或者應該跳到外循環檢查code
3. 不要忘記更新下標blog
class Solution(object): def isPalindrome(self, s): if not s or s == '': return True i, j = 0, len(s) - 1 while i <= j: while i < len(s) and not s[i].isalnum(): i += 1 while j >= 0 and not s[j].isalnum(): j -= 1 if i == len(s) or j < 0: break if s[i].isalpha() and s[j].isalpha() and s[i].lower() == s[j].lower() or s[i].isdigit() and s[j].isdigit() and s[i] == s[j]: pass else: return False i += 1 j -= 1 return True
對比相同方法別人的代碼,能夠有如下改動:
class Solution(object): def isPalindrome(self, s): i, j = 0, len(s) - 1 while i <= j: while i < j and not s[i].isalnum(): i += 1 while i < j and not s[j].isalnum(): j -= 1 if s[i].lower() != s[j].lower(): return False i += 1 j -= 1 return True
別人還有更pythonic可是須要額外空間複雜度的作法,很贊,平時工做徹底能寫得出,可是刷題時就忘記了:
class Solution(object): def isPalindrome(self, s): cleanlist = [c for c in s.lower() if c.isalnum()] return cleanlist == cleanlist[::-1]
2/18/2017, Java
注意Java Character各類函數
1 public class Solution { 2 public boolean isPalindrome(String s) { 3 if (s == null) return true; 4 int start = 0, end = s.length() - 1; 5 char c1, c2; 6 boolean isDigitS, isLetterS, isDigitE, isLetterE; 7 while (start <= end) { 8 c1 = s.charAt(start); 9 isDigitS = Character.isDigit(c1); 10 isLetterS = Character.isLetter(c1); 11 if (!isDigitS && !isLetterS) { 12 start++; 13 continue; 14 } 15 c2 = s.charAt(end); 16 isDigitE = Character.isDigit(c2); 17 isLetterE = Character.isLetter(c2); 18 if (!isDigitE && !isLetterE) { 19 end--; 20 continue; 21 } 22 if (isDigitE && isDigitS && c1 == c2 || isLetterS && isLetterE && Character.toLowerCase(c1) == Character.toLowerCase(c2)) { 23 start++; 24 end--; 25 continue; 26 } 27 return false; 28 } 29 return true; 30 } 31 }