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; } |
boolean flag = true;
String string = s.replaceAll(“[^_a-zA-Z0-9_:]”, “”);
String string2 = string.replaceAll(“[:_]” , “”).toLowerCase();
// 1 full string amanaplanacanalpanama
StringBuilder sb = new StringBuilder(string2);
sb.reverse();
if(string2.equals(sb.toString())) // comparing every character in the string
return flag;
return flag = false;
I recently gave a Mock Interview on findnewton.com and it was a pretty good experience.
The interviewer asked me 2 set of programming questions and 2 behavioural questions.
Post the interview I received detailed feedback and also got referral to my dream company.
how can one check the commas exclamation marks etc.
how will you remove/check the commas symbols in this.
var x = "Red rum, sir, is murder"
x = x.replace(/[ ,]/g,"").toLowerCase()
var mid = x.length/2
var res = null
if(x.length % 2 == 0){
res = x.slice(0,mid).split("").reverse("").join("") == x.slice(mid)
}
else {
res= x.slice(0,mid).split("").reverse("").join("") == x.slice(mid+1)
}
console.log(res);
Accepted solution. Easier to understand as well:
public boolean isPalindrome(String s) {
if(s == null || s.isEmpty()) {
return true;
}
int start = 0; int end = s.length() – 1;
while(start <= end) {
Character first = s.charAt(start);
Character last = s.charAt(end);
if(!Character.isLetterOrDigit(first)) {
start++;
continue;
}
if(!Character.isLetterOrDigit(last)) {
end–;
continue;
}
if(Character.isLetterOrDigit(first) && Character.isLetterOrDigit(last)) {
if(Character.toLowerCase(first) != Character.toLowerCase(last)) {
return false;
}
start++;
end–;
}
}
return true;
}
Using string buffer ,
import java.util.*;
import java.lang.*;
class Seventeen
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String str=sc.next();
String reverse = new StringBuffer(str).reverse().toString();
if(str.equals(reverse))
System.out.println(“true”);
else
System.out.println(“false”);
}
}
Solution 3 should stop at s.length()/2 :
public boolean isPalindrome(String s) {
s = s.toLowerCase();
s = s.replaceAll("[^a-z0-9]","");
for (int i=0; i < s.length()/2; i++){
if (s.charAt(i) != s.charAt(s.length()-i-1))
return false;
}
return true;
}
static boolean isValidPalidrome(String str) {
int i = 0;
int j = str.length() - 1;
while (i = 'a' && a = 'A' && a <= 'Z')) {
return true;
} else {
return false;
}
}
public class palindrom {
public static boolean isPalindrom(String s){
int end = s.length()-1;
for( int i =0 ; i < s.length()/2 ; i++){
if(s.charAt(i) != s.charAt(end))
return false;
end--;
}
return true;
}
public static void main(String[] args)
{
System.out.println(isPalindrom("0madanadam0"));
}
}
I still see this error. Also, is there anything wrong with using the StringBuilder()’s reverse method that a couple people have suggested in the comments?
public class Solution {
public boolean isPalindrome(String s) {
s = s.replaceAll(“[^a-zA-Z0-9]”, “”).toLowerCase();
String rev = new StringBuilder(s).reverse().toString();
if(s.equals(rev))
return true;
else return false;
}
}
How is this is as a solution? Any flaws?
Hey this is my solution, is not a big deal hehe just a simple for and StringBuilder
public boolean isPalindrome(String s) {
s = s.toLowerCase();
StringBuilder builder = new StringBuilder();
for(int index = 0; index < s.length(); index++) {
Character temp = s.charAt(index);
if(Character.isLetterOrDigit(temp)) {
builder.append(temp.toString());
}
}
String tempString = builder.toString();
String otherString = builder.reverse().toString();
if(tempString.equals(otherString)) return true;
return false;
}
how about ?
if (s.Length % 2 != 0)
{
return false;
}
Your solution 1 will throw:
Error:(.. , ..) java: variable left might not have been initialized
Error:(.. , ..) java: variable right might not have been initialized
Your solution 3:
The for loop is not best choice here. You are comparing two times the same character.
When i = 0,
you compare charAt(0) with charAt(s.length() – 1)
When i = s.length() – 1
you compare charAt(s.length() – 1) and charAt(0)
While loop is recommended
Cool!
We could use too ():
public static boolean isPalindrome(String s) {
String pureString = s.replaceAll(“[^A-Za-z0-9]”, “”);
if(pureString.length() == 0)
return false;
return(pureString.toLowerCase().equals(new StringBuilder(pureString.toLowerCase()).reverse().toString()));
}
public static boolean isPolindrome(String s) {
s = s.replaceAll(“[^a-zA-Z]”, “”);
return (s.equalsIgnoreCase(new StringBuilder(s).reverse().toString()));
}
I have a question that if the string is empty the statement s.length()==0 would be true, it will return false. Is this wrong?
Solution 3 is the most intuitive one when I think of this problem, but you can easily make its performance split in half by doing the iteration from i=0 to s.length() / 2, because at the moment each character is compared twice, i.e for “abcd” you compare “a” == “d” but at the end also “d” == “a”
Right. Thanks for pointing out this problem. I have changed the code.
Great, Thanks! It is added!
Here is an easier solution using two pointers
public static boolean isPalindrome1(String s) {
s = s.replaceAll(“[^0-9a-zA-Z]”, “”).toLowerCase();
int start = 0;
int end = s.length() – 1;
while (start < end){
if (s.charAt(start) != s.charAt(end)){
return false;
}
start++;
end–;
}
return true;
}
this is a great solution, thanks for sharing!
public class ValidPalindrome {
public static boolean isValidPalindrome(String s){
if(s==null||s.length()==0) return false;
s = s.replaceAll(“[^a-zA-Z0-9]”, “”).toLowerCase();
System.out.println(s);
for(int i = 0; i < s.length() ; i++){
if(s.charAt(i) != s.charAt(s.length() – 1 – i)){
return false;
}
}
return true;
}
public static void main(String[] args) {
String str = "A man, a plan, a canal: Panama";
System.out.println(isValidPalindrome(str));
}
}
Hi, I found that there are two redundant lines in your first solution. These two lines
“left = charArray[i];
right = charArray[j];”
seem to be redundant in the largest while loop, because you have already changed them in the above two while loops.
Great Solution! Thanks.
Here is the idea that remove non-letter first
public class Solution {
public boolean isPalindrome(String s) {
s = s.replaceAll(“[^a-zA-Z0-9]”, “”);
s = s.toLowerCase();
int len = s.length();
if(len<2)
return true;
Stack sta = new Stack();
int index = 0;
while(index < len/2){
sta.push(s.charAt(index));
index ++;
}
if (len%2 ==1)
index++;
while(index < len){
if(sta.empty())
return false;
char temp = sta.pop();
if(s.charAt(index) != temp)
return false;
else
index ++;
}
return true;
}
}