DEV Community

tommy-3
tommy-3

Posted on • Edited on

Learning Algorithms with JS, Python and Java 2: Palindrome

Here's my second attempt at solving the same problem using three different languages: JavaScript, Python and Java.

Today's question is to judge whether the given string is a palindrome.

1 The Most Straightforward Solution

JavaScript:

function isPalindrome(str) {
    const reversed = str.split('').reverse().join('');
    return str === reversed;
}
Enter fullscreen mode Exit fullscreen mode

Python:

def is_palindrome(str):
    return str[::-1] == str
Enter fullscreen mode Exit fullscreen mode

Java:

static boolean isPalindrome(String str) {
    String reversed = new StringBuilder(str).reverse().toString();
    return reversed.equals(str);
}
Enter fullscreen mode Exit fullscreen mode

Note that return reversed == str; doesn't work because reversed and str point to different objects.

2. Elegant (But Redundant)

JavaScript:

function isPalindrome(str) {
    return str.split('').every((char, i) => {
        return char === str[str.length - i - 1];
    });
}
Enter fullscreen mode Exit fullscreen mode

Its Python equivalent, without redundancy, would be perhaps:

def is_palindrome(str):
    return all([str[i] == str[-i-1] for i in range(len(str)//2)])
Enter fullscreen mode Exit fullscreen mode

And Java:

static boolean isPalindrome(String str) {
    int n = str.length();
    return IntStream.range(0, n/2)
            .allMatch(i -> str.charAt(i) == str.charAt(n - i - 1));
}
Enter fullscreen mode Exit fullscreen mode

3. An Alternative With a For Loop

JavaScript:

function isPalindrome(str) {
    const n = str.length;
    for (let i = 0; i < Math.floor(n/2); i++) {
        if (str[i] != str[n - i - 1]) {
            return false;
        }
    }
    return true;
}
Enter fullscreen mode Exit fullscreen mode

Python:

def is_palindrome(str):
   for i in range(len(str)//2):
         if str[i] != str[-i-1]:
                 return False
   return True
Enter fullscreen mode Exit fullscreen mode

Java:

static boolean isPalindrome(String str) {
    int n = str.length();
    for (int i = 0; i < n / 2; i++)
        if (str.charAt(i) != str.charAt(n - i - 1)) {
            return false;
        }
    return true;
}
Enter fullscreen mode Exit fullscreen mode

Notes:
5 / 2 is 2.5 in JavaScript and Python 3.
5 / 2 is 2 in Java.
5 // 2 is 2 in Python 3.

References:
https://stackoverflow.com/questions/11758791/python-3-2-palindrome
https://stackoverflow.com/questions/4138827/check-string-for-palindrome

Top comments (0)