0

I don't even know where to start on this one, as in what methods from Linq to use, but i have an example.

If the string would be "xxyxxz", this would be the output (though not necessarily in this order):

x x y x x z xx xx xyx xxyxx

Does anyone have any idea how to solve this?

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215

1 Answers1

1

If string is not very long, you can try brute force: enumerate all substrings and filter out palindromes. Let's implement pure Linq for this:

  using System.Linq;

  ...

  string source = "xxyxxz";

  var result = Enumerable
    .Range(1, source.Length)                 // all substrings' lengths
    .SelectMany(length => Enumerable         // all substrings 
       .Range(0, source.Length - length + 1)
       .Select(i => source.Substring(i, length)))
    .Where(item => item.SequenceEqual(item.Reverse())) // Linq to test for palindrome
    .ToArray(); // Let's have an array of required substrings

  // Let's have a look at the result:
  Console.Write(string.Join(" ", result));

Outcome:

  x x y x x z xx xx xyx xxyxx
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • And if it is longer, what could i do in a more optimized way? –  Jun 18 '20 at 11:28
  • @pink_totoro: for *enumerating* substrings in the *worst case* (`"aaaa...a"` - all characters are equal) you'll have a huge answer: `n * (n + 1) / 2` substrings to output; *counting* such substrings (int the example above the answer is `10`) is easier problem https://leetcode.com/problems/palindromic-substrings/ – Dmitry Bychenko Jun 18 '20 at 11:34
  • Assuming there are no [grapheme cluster](https://stackoverflow.com/a/15111719/1336590) shenanigans in the mix. – Corak Jun 18 '20 at 11:39
  • @Corak: yes; the first issue is case; moreover unicode strings are complex stuff (same letters can be represent in different ways). Often such (academic) problems assume that string is all small English characters – Dmitry Bychenko Jun 18 '20 at 11:43