LeetCode – Valid Palindrome (Java)
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example, "Red rum, sir, is murder"
is a palindrome, while "Programcreek is awesome"
is not.
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.
Java Solution
There are several different ways to solve this problem. The following is a solution with O(n) time complexity and O(1) space complexity.
public boolean isPalindrome(String s) { if(s==null){ return false; } s = s.toLowerCase(); int i=0; int j=s.length()-1; while(i<j){ while(i<j && !((s.charAt(i)>='a' && s.charAt(i)<='z') || (s.charAt(i)>='0'&&s.charAt(i)<='9'))){ i++; } while(i<j && !((s.charAt(j)>='a' && s.charAt(j)<='z') || (s.charAt(j)>='0'&&s.charAt(j)<='9'))){ j--; } if(s.charAt(i) != s.charAt(j)){ return false; } i++; j--; } return true; } |
<pre><code> String foo = "bar"; </code></pre>
-
Pradeep Gupta
-
Prateek Saxena
-
Prateek Saxena
-
Kaushlendra Singh
-
Sonali
-
Sumedha Prathipati
-
Milan
-
Ravi Tiwari
-
Kshama Dalal
-
Randy Lutcavich
-
Varun Shetty
-
Diego
-
Sunil Vurity
-
Arnaud Hebert
-
Chris
-
Tiago Pinho
-
chenk
-
JOY
-
eranyanay
-
ryanlr
-
ryanlr
-
April
-
Jarvis
-
Frank
-
Diana Du
-
ryanlr
-
tia