# Finding “sub-palindromes”.

The shortest code that finds all unique "sub-palindromes" of a string, that is: any substring with length > 1 that is a palindrome.

eg.1

input: "12131331"
output: "33", "121", "131", "313", "1331"


eg.2

input: "3333"
output: "33", "333", "3333"

• Can a string be it's own sub-palindrome? Since a string is it's own substring. – JPvdMerwe Jan 29 '11 at 12:17
• @JPvdMerwe: Yes, off course. – Eelvex Jan 29 '11 at 12:39
• Actually more importantly: what must the output of 333 be? Naively you'd end up printing 33 twice – JPvdMerwe Jan 29 '11 at 12:41
• @JPvdMerwe: '333' -> '33', '333'. I'll edit the question accordingly. Thanks. – Eelvex Jan 29 '11 at 12:53
• How is the output specified? Comma-delimited with quotes areound each sub-palindrome as you demonstrate here? One sub-p per line? – Joey Jan 30 '11 at 12:58

# Java 8, 202201 199 bytes

import java.util.*;s->{Set r=new HashSet();String x;for(int l=s.length(),i=0,j;i<l;i++)for(j=i;++j<=l;)if((x=s.substring(i,j)).contains(new StringBuffer(x).reverse())&x.length()>1)r.add(x);return r;}


Try it here.

If a function isn't allowed and a full program is required, it's 256 255 253 bytes instead:

import java.util.*;interface M{static void main(String[]a){Set r=new HashSet();String x;for(int l=a[0].length(),i=0,j;i<l;i++)for(j=i;++j<=l;)if((x=a[0].substring(i,j)).contains(new StringBuffer(x).reverse())&x.length()>1)r.add(x);System.out.print(r);}}


Try it here.

Explanation:

import java.util.*;      // Required import for Set and HashSet

s->{                     // Method with String parameter and Set return-type
Set r=new HashSet();   //  Return-Set
String t;              //  Temp-String
for(int l=s.length(),  //  Length of the input-String
i=0,j;         //  Index-integers (start i at 0)
i<l;i++)           //  Loop (1) from 0 to l (exclusive)
for(j=i;++j<=l;)     //   Inner loop (2) from i+1 to l (inclusive)
if((t=s.substring(i,j)
//    Set t to the substring from i to j (exclusive)
).contains(new StringBuffer(t).reverse())
//    If this substring is a palindrome,
&t.length()>1)  //    and it's length is larger than 1:
//   End of inner loop (2) (implicit / single-line body)
//  End of loop (1) (implicit / single-line body)
return r;              //  Return the result-Set
}                        // End of method


# JavaScript (ES6), 107 bytes

Returns a Set.

s=>new Set((g=(s,r=[...s].reverse().join)=>s[1]?(r==s?[s]:[]).concat(g(s.slice(1)),g(r.slice(1))):[])(s))


### Test cases

let f =

s=>new Set((g=(s,r=[...s].reverse().join)=>s[1]?(r==s?[s]:[]).concat(g(s.slice(1)),g(r.slice(1))):[])(s))

console.log([...f('12131331').values()])
console.log([...f('3333').values()])

# Stax, 10 bytes

îmmW┴√▄○○←


Run and debug it

I couldn't find an is-palindrome function. With that this'd probably be much shorter.