Why is the Java solution slower than the Python one?

  • 0

    // Java 532ms

    public class Solution {
        public boolean isPalindrome(String s) {
            s = s.toLowerCase().replaceAll("[^a-z0-9]", "");
        	int tail = s.length()-1; 
        	for(int head=0; head<tail; head++,tail--){
    				return false;
        	return true;

    //Python 252 ms

    class Solution:
        # @param s, a string
        # @return a boolean
        def isPalindrome(self, s):
            r= [i.lower() for i in s if i.isalnum()]
            return r == r[::-1]

    Where I can keep improving the performance of the Java version? If not, why?

  • 0

    for the java version, i guess there's no need to replace all non-alphanumeric to "", you can just ignore them when loop.

  • 0

    thanks for the hint, I had actually tried the "ignore" either, but it got even slower...

Log in to reply

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