在由数字组成的字符串中查找未知的重复模式 [英] Finding unknown repeating patterns in a string consisting numbers
问题描述
我已经为此苦苦挣扎了一个星期.
I've been struggling with this for a week.
我有一个这样的字符串:1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1.....
I have a string like this: 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1.....
我需要找到什么:1 1 0
示例 2:1 1 2 0 2 2 1 0 1 1 2 0 2 2 1 0 1 1 2 0 2 2 1 0 1 1 2 0 2 2 1 0 ....
我需要找到什么:1 1 2 0 2 2 1 0
示例 3:1 1 2 3 1 0 1 1 2 3 1 0 1 1 2 3 1 0 1 1 2 3 1 0 1 1 2 3 1 0...
112310
等等.等
我现在的代码:
private string tekrarArama(double[] mods)
{
string part1 = "";
string part2 = "";
string patern = "";
int number1 = mods.Length;
for (int i = 0; i < mods.Length; i++)
{
part1 = "";
part2 = "";
for (int j = 0; j < number1; j++)
{
part1 += mods[j] + ",";
}
for (int k = 0; k < mods.Length; k++)
{
part2 += mods[k] + ",";
}
int actualcount = Regex.Matches(part2, part1).Count;
int count = part2.Replace(",", "").Length / part1.Replace(",", "").Length;
if (part2.IndexOf(bolum1) >= 0 && actualcount == count )
{
patern = part2.Substring(part2.IndexOf(part1),part1.Length);
}
number1--;
}
return patern;
}
它创建字符串的两个副本,并在每次迭代中从其中一个字符串中一次删除 1 个字符,以找到最小的重复模式.
It creates two copies of the string and deletes 1 character at a time from one of the strings in each iteration, to find the smallest repeating pattern.
这是一团糟,根本不能很好地工作.我怎样才能做到这一点?提前致谢.
It's a mess and doesn't work very well at all. How can I do this? Thanks in advance.
推荐答案
如果您正在寻找简单的东西并且不需要最佳的复杂性,这里有一种简洁的方式来表示查询.
If you're looking for something simple and don't need optimal complexity, here's a concise way to represent the query.
string FindPattern(string text)
{
if (text == null)
{
return null;
}
return Enumerable
.Range(1, text.Length / 2)
.Where(n => text.Length % n == 0)
.Select(n => text.Substring(0, n))
.Where(pattern => Enumerable
.Range(0, text.Length / pattern.Length)
.SelectMany(i => pattern)
.SequenceEqual(text))
.FirstOrDefault();
}
请注意,这里的复杂度在最坏的情况下是二次的,因此将其用于很长的字符串并不是一个好主意.
Note that the complexity here is quadratic in the worst case, so it's not a good idea to use it for very long strings.
这篇关于在由数字组成的字符串中查找未知的重复模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!