A Collection of Code Snippets in as Many Programming Languages as Possible
This project is maintained by TheRenegadeCoder
Welcome to the Longest Palindromic Substring in Mathematica page! Here, you'll find the source code for this program as well as a description of how the program works.
(* Code *)
(* Brute force approach of generating all substrings and testing: *)
longestPalindromicSubstring = word \[Function] First @ MaximalBy[
Select[PalindromeQ][
Flatten[Table[
StringTake[word, {i, j}],
{i, 1, StringLength[word]}, {j, i + 1, StringLength[word]}],
1]],
StringLength,
UpTo[1]];
(* The outer function provides the 'user interface' (e.g., the string parsing): *)
longestPalindromicSubstringMain = Function[{s},
Module[{e = "Usage: please provide a string that contains at least one palindrome"},
Catch[
longestPalindromicSubstring @
If[StringLength[s] > 0, s, Throw[e]]]]];
(* Valid Tests *)
Print /@ longestPalindromicSubstringMain /@ {
"racecar",
"kayak mom",
"step on no pets"
};
(* Invalid Tests *)
longestPalindromicSubstringMain[""]
Longest Palindromic Substring in Mathematica was written by:
If you see anything you'd like to change or update, please consider contributing.
No 'How to Implement the Solution' section available. Please consider contributing.
No 'How to Run the Solution' section available. Please consider contributing.