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;
}

28 thoughts on “LeetCode – Valid Palindrome (Java)”

  1. 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;

  2. 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.

  3. 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);

  4. 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;
    }

  5. 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”);
    }
    }

  6. 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;
    }


  7. 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;
    }
    }


  8. 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"));
    }
    }

  9. 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?

  10. 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;

    }

  11. 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

  12. 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()));
    }

  13. public static boolean isPolindrome(String s) {
    s = s.replaceAll(“[^a-zA-Z]”, “”);
    return (s.equalsIgnoreCase(new StringBuilder(s).reverse().toString()));
    }

  14. 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?

  15. 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”

  16. 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;

    }

  17. 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));

    }

    }

  18. 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.

  19. 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;

    }

    }

Leave a Comment