一种方法的实现,使用给定的字符串,使用 Linq 方法生成所有可能的回文分区
Implementation for a method that, with a given string, generates all its possible partitions that are a palindrome, using Linq methods
我什至不知道从哪里开始这个,因为要使用 Linq 中的哪些方法,但我有一个例子。
如果字符串是 "xxyxxz"
,这将是输出(尽管不一定按此顺序):
x x y x x z xx xx xyx xxyxx
有人知道如何解决这个问题吗?
如果字符串不是很长,可以尝试蛮力:枚举所有子串,过滤掉回文。让我们为此实现纯 Linq:
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));
结果:
x x y x x z xx xx xyx xxyxx
我什至不知道从哪里开始这个,因为要使用 Linq 中的哪些方法,但我有一个例子。
如果字符串是 "xxyxxz"
,这将是输出(尽管不一定按此顺序):
x x y x x z xx xx xyx xxyxx
有人知道如何解决这个问题吗?
如果字符串不是很长,可以尝试蛮力:枚举所有子串,过滤掉回文。让我们为此实现纯 Linq:
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));
结果:
x x y x x z xx xx xyx xxyxx