仅使用LINQ的最长重复子序列 [英] Longest repeating subsequence using only LINQ

查看:98
本文介绍了仅使用LINQ的最长重复子序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你不能使用任何循环,if-else,try-catch,recursion等。

你可以重叠。在序列1111中,最长重复是111.在序列11211中 - 最长重复是11.



LongestRepetition(new [] {1,2,1,2} ,1,2,3,2,1,2})应该返回新的[] {1,2,1,2}。



我是什么尝试过:



我不知道该尝试什么。我解决了它没有LINQ。



这是我的代码:



You can't use any loops, if-else, try-catch, recursion and ect.
You can overlaps. In the sequence 1111 the longest repetition is 111. In the sequence 11211 - the longest repetition is 11.

LongestRepetition(new [] {1, 2, 1, 2, 1, 2, 3, 2, 1, 2}) should return new [] {1, 2, 1, 2}.

What I have tried:

I don't know what to try. I solved it without LINQ.

that's my code:

static string LongestRepetition(string str)
        {
            var list = new List<string>();
            var counter = 0;
            var rep = "";

            for (int i = 0; i < str.Length; i++)
            {
                rep = "";
                for (int k = i; k < str.Length; k++)
                {
                    counter = 0;
                    rep += str[k];
                    var startIndex = 0;
                    var indexOf = int.MinValue;
                    while ((indexOf = str.IndexOf(rep, startIndex)) >= 0)
                    {
                        counter++;
                        startIndex = indexOf + 1;
                        if (counter > 1) break;
                    }

                    if (counter > 1)
                    {
                        list.Add(rep);
                    }
                }
            }

            return list.OrderByDescending(x => x.Length).FirstOrDefault();
        }

推荐答案

会员13711733 [ ^ ]写道:

LongestRepetition(new [] {1,2,1,2} ,1,2,3,2,1,2})应返回 new [] {1,2,1,2}





为什么?它应该在逻辑上返回 new [] {1,2,1,2,1,2} ,因为它是最长的重复。



检查此通用linq解决方案:



Why? It should logically return new [] {1, 2, 1, 2, 1, 2}, because it's a longest repetition.

Check this generic linq solution:

public static T[] GetLongestRepetition<T>(T[] list)
{
	
	return list.TakeWhile(o => list.GroupBy(x=>x)
				.Where(grp=>grp.Count()>1)
				.Any(grp=>grp.Key.Equals(o)))
		.ToArray();
}



用法:


Usage:

int[] nums = new int[]{1, 2, 1, 2, 1, 2, 3, 2, 1, 2};
var result = GetLongestRepetition(nums);
Console.WriteLine("{0}", string.Join("", result)); //prints 121212
	
string s = "aabaa";
var result1 = GetLongestRepetition(s.ToArray());
Console.WriteLine("{0}", string.Join("", result1)); //prints aa

string num = "1123811238479";
var result2 = GetLongestRepetition(num.ToArray());
Console.WriteLine("{0}", string.Join("", result2)); //prints 1123811238





注意#1:这个解决方案不幸地使用了隐藏循环,参见: TakeWhile [ ^ ]



注意#2:我没有足够的时间来测试我的解决方案。 因此,它可能需要改进......



Note #1: This solution, unfortunatelly, uses a "hidden loop", see: TakeWhile[^]

Note #2: I haven't enough time to test my solution. So, it may need improvements...


这篇关于仅使用LINQ的最长重复子序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆