Valid palindrome
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"IsNotA 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.
Algorithm ideas:
Train of Thought 1: scanning and judgment based on the original string with two pointers at the beginning and end. Space complexity O (1), time O (N), one scan.
1 public class Solution { 2 public boolean isPalindrome(String s) { 3 s = s.trim().toLowerCase(); 4 int i = 0; 5 int j = s.length() - 1; 6 while(i < s.length() && !isValid(s.charAt(i))) i++; 7 while(j >= 0 && !isValid(s.charAt(j))) j--; 8 while(i <= j){ 9 char a = s.charAt(i);10 char b = s.charAt(j);11 if(a != b){12 return false;13 }else{14 i++;15 while(i < s.length() && !isValid(s.charAt(i))) i++;16 j--;17 while(j >= 0 && !isValid(s.charAt(j))) j--;18 }19 }20 return true;21 }22 private boolean isValid(char c){23 if((c >= ‘a‘ && c <= ‘z‘) || (c >= ‘A‘ && c <= ‘Z‘) || (c >= ‘0‘ && c <= ‘9‘) ) return true;24 return false;25 }26 }
Train of Thought 2: scan for the first time, retain valid characters in another string S, and scan for the second time. Space complexity O (1), time complexity O (N), two scans.
Relatively simple, not implemented
[Leetcode] valid palindrome