gpt4 book ai didi

C# 字符串排列

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:45:09 24 4
gpt4 key购买 nike

我有像 1,2|3,41|2,3|4 这样的字符串,需要从它们中获取以下排列(作为数组/列表)。

给定 1,2|3,4 需要得到 2 个字符串:1,2,41,3,4

给定 1|2,3|4 需要得到 4 个字符串:1,31,42,32,4

它基本上是在逗号上拆分,然后如果这些元素有管道,则为每个管道分隔的子元素(剩余元素的)创建排列。该解决方案需要处理带有管道的元素数量未知的一般情况。

对使用标准 C# 库的任何解决方案感兴趣。

卡在这个问题上,所以从社区中寻找一些想法。我似乎无法通过带有管道的元素......它几乎就像需要“向前看”或者我需要用剩余的逗号分隔元素(其中一些可能有管道,这使得我想到了递归,但仍然无法理解它)。

最终顺序无关紧要。逗号和竖线分隔的元素是数字(存储字符串),最后的字符串顺序无关紧要,所以 1,2,4 = 1,4,2

不,这不是家庭作业。学校在十多年前就结束了。

最佳答案

我们可以使用 LINQ 以一种奇特的方式做到这一点。首先,我们需要 Eric Lippert 的 CartesianProduct扩展方法:

static IEnumerable<IEnumerable<T>> CartesianProduct<T>( this IEnumerable<IEnumerable<T>> sequences )
{
IEnumerable<IEnumerable<T>> emptyProduct =
new[] { Enumerable.Empty<T>() };

return sequences.Aggregate(
emptyProduct,
( accumulator, sequence ) =>
from accseq in accumulator
from item in sequence
select accseq.Concat( new[] { item } ) );
}

然后我们可以简单地做:

var a = "1|2,3|4".Split( ',' );
var b = a.Select( x => x.Split( '|' ) );
var res = b.CartesianProduct().Select( x => string.Join( ",", x ) );

我们完成了!

关于C# 字符串排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28073324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com