30
2
This is a mirror: |
. I just found out that you can stick a mirror in the middle of a string if the string can be mirrored on itself! For example, the string abccba
. If you cut it in half the two halves are mirror images of each other:
abc <--> cba
So, we can stick a mirror in the middle of the string, and our new string is abc|cba
. Sometimes, only part of the string can be mirrored on itself. For example, the string "mirror". The two r's are mirrored, but the rest of the string isn't. That's OK, we'll just remove the parts of the string that don't mirror each other, and we get the following string:
r|r
Some strings could be mirrored in multiple places. For example, "Hello World, xyzzyx". I like having a lot of text reflected in my mirror, so you need to find the best place to put my mirror. In this case, you should output the longer mirrored string and just like our last example, remove everything else. This string becomes:
xyz|zyx
Some strings look like they can be mirrored, but actually can not. If a string cannot be mirrored anywhere, you should output nothing.
The challenge:
Given a string containing only printable-ascii, find the best place to put my mirror. In other words,
Find the largest even-length palindromic substring, then output it with a pipe character '|' in the middle of it.
The input will be 1-50 characters long.
You can assume that the input will not contain mirrors |
or newlines. Beyond that, all printable-ascii characters are fair game. If the longest mirrored substring is tied between two substrings, you can choose which one to output. For example, for the string "abba ollo", you must output "ab|ba" or "ol|lo", but it doesn't matter which one you output. Strings are case-sensitive, e.g. "ABba" should not output "AB|ba", it should output the empty string.
Sample IO:
"Hello World" --> "l|l"
"Programming Puzzles and Code-Golf" --> Either "m|m" or "z|z"
"abcba" --> ""
"Hulluh" --> "ul|lu"
"abcdefggfedcba" --> "abcdefg|gfedcba"
"abcdefggfabc" --> "fg|gf"
"AbbA" --> "Ab|bA"
"This input is a lot like the last one, but with more characters that don't change the output. AbbA" --> "Ab|bA"
As usual, this is code-golf, so standard loopholes apply, and the shortest answer in bytes wins!
Is there a limit on the length of the input? – Mego – 2016-07-04T01:27:18.807
@Mego As long as your algorithm theoretically works on any input, I don't care how long it takes/how much memory it takes. – James – 2016-07-04T01:36:57.130
I asked because vanilla regex engines are only capable of matching palindromes of length up to a specified, finite value (as opposed to arbitrarily-long palindromes), and the possibility of a regex-based solution would depend on whether or not there is an upper bound on the length of the input. – Mego – 2016-07-04T01:40:23.150
@Mego Ah, that makes sense. Let's say the input can be up to 50 characters long. How does that sound? – James – 2016-07-04T02:03:21.837