DEV Community

Reverse a Word.

Awdesh on July 25, 2018

I wrote couple of posts previously here and here on how to find duplicates in an array and we saw different variety of that problem. I want to sw...
Collapse
 
dallgoot profile image
dallgoot

very , very small optimization :p

public static boolean isPalindrome(String input)
{
    char[] charArray = input.toCharArray();
    int cursor = 0;
    int max = input.length() - 1;

    while(cursor <= max && charArray[cursor] == charArray[max-cursor])
    {
        cursor++;
    }
    return cursor > max; 
}

if by any chance you can benchmark the 2 versions : me very glad ;)

Collapse
 
caubeen profile image
caubeen • Edited

JavaScript!!

const palindrome = string => [...string].reverse().join('') === string
Collapse
 
justinenz profile image
Justin

Go! This was a fun challenge as I'm fairly new to Go =) Feedback is welcomed!

package main

import (
    "fmt"
    "os"
    "strings"
)

func main() {
    var phraseList = os.Args[1:]
    for index := range phraseList {
        fmt.Printf("%s :: %s :: %t\n",
            phraseList[index],
            reverse(phraseList[index]),
            isPalindrome(phraseList[index]))
    }
}

func reverse(phrase string) string {
    var phraseBytes = []byte(phrase)
    var phraseLenght = len(phraseBytes) - 1
    var tempChar byte
    for index := 0; index < len(phraseBytes)/2; index++ {
        tempChar = phraseBytes[index]
        phraseBytes[index] = phraseBytes[phraseLenght-index]
        phraseBytes[phraseLenght-index] = tempChar
    }
    return string(phraseBytes)
}

func isPalindrome(phrase string) bool {
    return strings.Replace(phrase, " ", "", -1) ==
        strings.Replace(reverse(phrase), " ", "", -1)
}

C:\go\src\reverse> .\reverse reverse four three "taco cat"
reverse :: esrever :: false
four :: ruof :: false
three :: eerht :: false
taco cat :: tac ocat :: true

Collapse
 
msafadieh profile image
Mohamad

Python!!

def palindrome(string):
    return all(string[i] == string[-i-1] for i in range(len(string)//2))
Collapse
 
rubberduck profile image
Christopher McClellan

Here’s a challenge for you. You wrote the same loop twice. Could you write a function that takes an anonymous function as an arg so you never have to write this “dual ended” loop again?

Collapse
 
_hs_ profile image
HS

why not just this
public static boolean isPalindrome(String str) {
return str.equals(new StringBuilder(str).reverse().toString());
}

Collapse
 
s_awdesh profile image
Awdesh

You are using Java's in built reverse method. Normally in an interview, you create your own algorithm i.e. your own implementation of reverse method.

Collapse
 
_hs_ profile image
HS

Oh OK these post are like examples for juniors when doing interview and stuff