Longest palindromic substrings: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 11:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F longest_palindrome(s)
V t = Array(‘^’s‘$’).join(‘#’)
V n = t.len
Line 35:
‘drome’,
‘the abbatial palace’]
print(‘'’s‘' -> '’longest_palindrome(s)‘'’)</langsyntaxhighlight>
 
{{out}}
Line 48:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE FUNC Palindrome(CHAR ARRAY s)
BYTE l,r
 
Line 91:
Test("qwertyuiop")
Test("")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Longest_palindromic_substrings.png Screenshot from Atari 8-bit computer]
Line 106:
Palindromes of length 1 or more are detected, finds the left most palindrome if there are several of the same length.<br>
Treats upper and lower case as distinct and does not require the characters to be letters.
<langsyntaxhighlight lang="algol68">BEGIN # find the longest palindromic substring of a string #
# returns the length of s #
OP LENGTH = ( STRING s )INT: ( UPB s + 1 ) - LWB s;
Line 182:
test( "abcc", "cc" );
test( "abbccc", "ccc" )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 199:
=={{header|Arturo}}==
{{trans|Nim}}
<langsyntaxhighlight lang="rebol">palindrome?: function [str]-> str = join reverse split str
 
lps: function [s][
Line 228:
print [str "->" (0 < size palindromes)? -> join.with:", " palindromes
-> "X"]
]</langsyntaxhighlight>
 
{{out}}
Line 241:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">LPS(str){
found := [], result := [], maxL := 0
while (StrLen(str) >= 2 && StrLen(str) >= maxL){
Line 271:
output := v output
return output
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">db =
(
three old rotators
Line 290:
}
MsgBox % output
return</langsyntaxhighlight>
{{out}}
<pre>three old rotators > ["rotator"]
Line 303:
=={{header|F_Sharp|F#}}==
===Manacher Function===
<langsyntaxhighlight lang="fsharp">
// Manacher Function. Nigel Galloway: October 1st., 2020
let Manacher(s:string) = let oddP,evenP=Array.zeroCreate s.Length,Array.zeroCreate s.Length
Line 318:
match (Ʃ+evenP.[Ʃ])>g with true->fGe (Ʃ-evenP.[Ʃ]+1) (Ʃ+evenP.[Ʃ]) (Ʃ+1) |_->fGe n g (Ʃ+1)
(fGo 0 -1 0,fGe 0 -1 0)
</syntaxhighlight>
</lang>
 
===The Task===
<langsyntaxhighlight lang="fsharp">
let fN g=if g=[||] then (0,0) else g|>Array.mapi(fun n g->(n,g))|>Array.maxBy snd
let lpss s=let n,g=Manacher s in let n,g=fN n,fN g in if (snd n)*2+1>(snd g)*2 then s.[(fst n)-(snd n)..(fst n)+(snd n)] else s.[(fst g)-(snd g)+1..(fst g)+(snd g)]
let test = ["three old rotators"; "never reverse"; "stable was I ere I saw elbatrosses"; "abracadabra"; "drome"; "the abbatial palace"; ""]
test|>List.iter(fun n->printfn "A longest palindromic substring of \"%s\" is \"%s\"" n (lpss n))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 340:
=={{header|Go}}==
{{trans|Wren}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 406:
fmt.Printf(" %-13s Length %d -> %v\n", s, len(longest[0]), longest)
}
}</langsyntaxhighlight>
 
{{out}}
Line 423:
A list version, written out of curiosity. A faster approach could be made with an indexed datatype.
 
<langsyntaxhighlight lang="haskell">-------------- LONGEST PALINDROMIC SUBSTRINGS ------------
 
longestPalindromes :: String -> ([String], Int)
Line 480:
where
rjust n c = drop . length <*> (replicate n c ++)
w = maximum (length . xShow <$> xs)</langsyntaxhighlight>
{{Out}}
<pre>Longest palindromic substrings:
Line 496:
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
<langsyntaxhighlight lang="jq">def longestPalindromicSubstring:
length as $len
| if $len <= 1 then .
Line 524:
| longestPalindromicSubstring as $longest
| " \(.): length \($longest[0]|length) -> \($longest)"
)</langsyntaxhighlight>
 
{{out}}
Line 540:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">function allpalindromics(s)
list, len = String[], length(s)
for i in 1:len-1, j in i+1:len
Line 557:
join(list[findall(x -> length(x) == length(list[end]), list)], "\" or \""), "\"")
end
</langsyntaxhighlight>{{out}}
<pre>
The longest palindromic substring of babaccd is: "bab" or "aba"
Line 568:
 
===Manacher algorithm===
<langsyntaxhighlight lang="julia">
function manacher(str)
s = "^" * join(split(str, ""), "#") * "\$"
Line 593:
"The longest palindromic substring of $teststring is: \"$pal\"")
end
</langsyntaxhighlight>{{out}}
<pre>
The longest palindromic substring of babaccd is: "aba"
Line 605:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[ExpandSubsequenceTry, LongestPalindromicSubsequence]
ExpandSubsequenceTry[seq_List, beginpos : {a_, b_}] :=
Module[{len, maxbroaden, last},
Line 638:
StringJoin@LongestPalindromicSubsequence[Characters["abracadabra"]]
StringJoin@LongestPalindromicSubsequence[Characters["drome"]]
StringJoin@LongestPalindromicSubsequence[Characters["the abbatial palace"]]</langsyntaxhighlight>
{{out}}
<pre>"rotator"
Line 649:
=={{header|Nim}}==
Simple algorithm but working on Unicode code points.
<langsyntaxhighlight Nimlang="nim">import sequtils, strutils, unicode
 
func isPalindrome(s: seq[Rune]): bool =
Line 679:
echo str, " → ", "<no palindromic substring of two of more letters found>"
else:
echo str, " → ", result.join(", ")</langsyntaxhighlight>
 
{{out}}
Line 692:
=={{header|Perl}}==
The short one - find all palindromes with one regex.
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Longest_palindromic_substrings
Line 705:
pop =~ /(.+) .? (??{reverse $1}) (?{ $best[length $&]{$&}++ }) (*FAIL)/x;
keys %{pop @best};
}</langsyntaxhighlight>
{{out}}
<pre>
Line 717:
</pre>
The faster one - does the million digits of Pi in under half a second.
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Longest_palindromic_substrings
Line 756:
I, man, am regal - a German am I
toot
Warsaw was raw</langsyntaxhighlight>
{{out}}
<pre>
Line 764:
=={{header|Phix}}==
{{trans|Raku}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo/rosetta/Longest_palindromic_substrings.exw (plus two older versions)</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 799:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">longest_palindromes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 819:
(This version ignores case but allows non-alphanumerics).
<langsyntaxhighlight lang="python">'''Longest palindromic substrings'''
 
 
Line 952:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Longest palindromic substrings:
Line 968:
This version regularizes (ignores) case and ignores non alphanumeric characters. It is only concerned with finding the ''longest'' palindromic substrings so does not exhaustively find ''all possible'' palindromes. If a palindromic substring is found to be part of a longer palindrome, it is not captured separately. Showing the longest 5 palindromic substring groups. Run it with no parameters to operate on the default; pass in a file name to run it against that instead.
 
<syntaxhighlight lang="raku" perl6line>my @chars = ( @*ARGS[0] ?? @*ARGS[0].IO.slurp !! q:to/BOB/ ) .lc.comb: /\w/;
Lyrics to "Bob" copyright Weird Al Yankovic
https://www.youtube.com/watch?v=JUQDzj6R3p4
Line 1,033:
}
 
"{.key} ({+.value})\t{.value.unique.sort}".put for @cpfoa.classify( *.chars ).sort( -*.key ).head(5);</langsyntaxhighlight>
{{out}}
Returns the length, (the count) and the list:
Line 1,053:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program finds and displays the longest palindromic string(s) in a given string. */
parse arg s /*obtain optional argument from the CL.*/
if s==''|s=="," then s='babaccd rotator reverse forever several palindrome abaracadaraba'
Line 1,078:
@= @ $ /*add a palindromic substring to a list*/
if short then return 1 /*we have found one palindrome. */
end /*j*/; return 0 /* " " " some palindrome(s). */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 1,132:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 1,161:
see "Longest palindromic substrings:" + nl
see resList
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,176:
 
The Phix entry examples have been used.
<langsyntaxhighlight lang="ecmascript">import "/seq" for Lst
import "/fmt" for Fmt
 
Line 1,204:
var longest = Lst.distinct(longestPalSubstring.call(s))
Fmt.print(" $-13s Length $d -> $n", s, longest[0].count, longest)
}</langsyntaxhighlight>
 
{{out}}
10,327

edits