My three line java solution


  • 51
    A
    public class Solution {
        public boolean isPalindrome(String s) {
            String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
            String rev = new StringBuffer(actual).reverse().toString();
            return actual.equals(rev);
        }
    }

  • 0
    I

    The code is neat, but its slower than the two pointer, still a nice approach

    Thank you


  • 0
    T

    Used the same approach, but instead of reversing and comparing, I checked characters from both ends using one pointer.

    Also, converting to lower case in not always necessary, For example : "Coding rocks"

    public static boolean isPalindrome(String s) {
    	String regex = "([^A-Za-z0-9])";
    	String replacement = "";
    	s = s.replaceAll(regex, replacement);
    	for(int i =0;i<s.length()/2;i++){
    		if(Character.toLowerCase(s.charAt(i))==Character.toLowerCase(s.charAt(s.length()-1-i)))
    			continue;
    		else 
    			return false;
    	}
    	return true;
    }
    

  • 0
    X
    This post is deleted!

  • 2

    String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();

    like this part!


  • 0
    X

    you missed the point of this question by using 'reverse()'


  • 0
    P

    Holy regex!!


  • 0
    G

    Dear Arunav2,

    by using built-in functions like here "reverse", it is useless to study algorithms here. Would you make your own pow(x,y) function just writing "return Math.pow(x,y);" ????

    sorry but this solution is a shame.


  • 0
    P

    Good idea! Thank you!


  • 0
    M

    can any one tell me how this line of code works:String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();


  • 0
    K

    Complexity for this will be O(N), you can improve this by reversing half of the palindrome
    e.g. KAYAK

    var MID = Y - This is your Pivot
    var Pre = KA
    var Post = AK

    If (Pre = REVERSE (Post ){
    Palindrome
    }else
    {
    not
    }

    This will reduce the complexity to half esp for long length string


  • 0
    S

    @mailtosrohit It's replacing all the non-alphanumeric characters with empty string.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.