Here is an example:
using System;
public class Program
{
private static bool istPalindrom(string word){
int i1 = 0;
int i2 = word.Length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
private static void FindPalindromes(string s)
{
// Assume a palindrome string is at least 2 characters
const int MinLength = 2;
if (s.Length <= MinLength)
{
return;
}
// Test all substrings by removing i first characters
for (int i = 0; i < s.Length - MinLength; i++)
{
string sub = s.Substring(i);
if (istPalindrom(sub))
{
Console.WriteLine($"Found palindrome: {sub}");
}
}
// Test all strings by the last character
FindPalindromes(s.Substring(0, s.Length - 1));
}
public static void Main()
{
FindPalindromes("ab12321bakjjkh3432");
}
}
which uses your istPalindrom
method to check (but with string
instead of char[]
). This tests all possible substrings of the given string. There are probably more efficient ways to do this, taking advantage of a palindrome of length n
must contain a palindrom of length n - 2
, meaning one could find all palindromes of length 3 and 4, and then try expanding those strings.
Output:
Found palindrome: 343
Found palindrome: kjjk
Found palindrome: ab12321ba
Found palindrome: b12321b
Found palindrome: 12321
Found palindrome: 232