Given a string, determine if it is a palindrome, considering only alphanumeric(字母和数字) characters and ignoring cases.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama"
Example 2:
Input: "race a car"
Output: false
Explanation: "raceacar"
O(n) time without extra memory.
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.
思路:
字符串中只考虑字母和数字是否构成一个回文串,no extra space可以定义两个指针。
注意:
if
statements then if the condition is true
all will be executed. If you have used if
and else if
combination only one will be executed where first comes the true value
代码:
1 public class Solution { 2 3 public boolean isPalindrome(String s) { 4 if (s == null || s.length() == 0) 5 return true; 6 7 int front = 0; 8 int end = s.length() - 1; 9 while (front < end) { 10 if (!isValid(s.charAt(front))) 11 front++; 12 else if (!isValid(s.charAt(end))) 13 end--; 14 else { 15 if (isValidCase(s.charAt(front), s.charAt(end))){ 16 front++; 17 end--; 18 } else { 19 return false; 20 } 21 } 22 23 } 24 return true; 25 } 26 27 public boolean isValid(char c) { 28 return Character.isLetter(c) || Character.isDigit(c); 29 } 30 public boolean isValidCase(char a, char b) { 31 if (a == b) 32 return true; 33 else if (Character.toUpperCase(a) == Character.toUpperCase(b)) 34 return true; 35 else 36 return false; 37 } 38 }
代码优化:
public class Solution { public boolean isPalindrome(String s) { if (s == null || s.length() == 0) { return true; } int front = 0; int end = s.length() - 1; while (front < end) { while (front < s.length() && !isvalid(s.charAt(front))) { // nead to check range of a/b front++; } if (front == s.length()) { // for empty string “.,,,” return true; } while (end >= 0 && ! isvalid(s.charAt(end))) { // same here, need to check border of a,b end--; } if (Character.toLowerCase(s.charAt(front)) != Character.toLowerCase(s.charAt(end))) { return false; } else { front++; end--; } } return true; } private boolean isvalid (char c) { return Character.isLetter(c) || Character.isDigit(c); } }
Lintcode415-Valid Palindrome-Medium
原文:https://www.cnblogs.com/Jessiezyr/p/10643865.html