Palindrome Coderbyte Solution

0

 Have the function Palindrome(str) take the str parameter being passed and return the string true if the parameter is a palindrome, (the string is the same forward as it is backward) otherwise return the string false. 

For example: "racecar" is also "racecar" backwards. Punctuation and numbers will not be part of the string.



Palindrome Coderbyte Solution in Java


import java.util.Scanner;

public class Palindrome {
String Palindrome(String str) {
String reversed = new StringBuilder(str).reverse().toString().replaceAll("\\s", "");
return str.replaceAll("\\s", "").equals(reversed) ? "true" : "false";
}

public static void main (String[] args) {
Scanner s = new Scanner(System.in);
Palindrome c = new Palindrome();
System.out.print(c.Palindrome(s.nextLine()));
}
}


Palindrome Coderbyte Solution in Python


def Palindrome(str):
string_no_spaces = str.replace(" ", "")
if string_no_spaces == string_no_spaces[::-1]:
return "true"
return "false"

Palindrome Coderbyte Solution in JavaScript

Using the JavaScript language, have the function Palindrome(str) take the str parameter being passed and return the string true if the parameter is a palindrome, (the string is the same forward as it is backward) otherwise return the string false. 

For example: "racecar" is also "racecar" backwards. Punctuation and numbers will not be part of the string.


function Palindrome(str) {

str = str.replace(/ /g,"").toLowerCase();
var compareStr = str.split("").reverse().join("");

if (compareStr === str) {
return true;
}
else {
return false;
}

}

Explanation

I have two outliers. The first is to remove all spaces between words since it can cause the reverse string to be wrong. The second is to convert string to lower case so that any capitalized words cause a false answer. I am going to first remove all spaces from the string. Then I am going to convert a new string that converts the modified str into an array and then reverses the contents and then converts it back to a string. I will compare the modified string and the newStr to see if they are equal signifying I have a Palindrome.  

Disclaimer: The above Problem is generated by Coderbyte but the Solution is provided by ShouterFolk.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !