使用.net?
在字符串中查找字符串中最长重复字符的最佳算法是什么答案 0 :(得分:4)
我猜你说的是模式发现。看看一些基本的方法(source)
private static Dictionary<string, int> FindPatterns(string value) {
List<string> patternToSearchList = new List<string>();
for (int i = 0; i < value.Length; i++) {
for (int j = 2; j <= value.Length / 2; j++) {
if (i + j <= value.Length) {
patternToSearchList.Add(value.Substring(i, j));
}
}
}
// pattern matching
Dictionary<string, int> results = new Dictionary<string, int>();
foreach (string pattern in patternToSearchList) {
int occurence = Regex.Matches(value, pattern, RegexOptions.IgnoreCase).Count;
if (occurence > 1) {
results[pattern] = occurence;
}
}
return results;
}
static void Main(string[] args) {
Dictionary<string, int> result = FindPatterns("asdxgkeopgkajdflkjbpoijadadafhjkafikeoadkjhadfkjhocihakeo");
foreach (KeyValuePair<string, int> res in result.OrderByDescending(r => r.Value)) {
Console.WriteLine("Pattern:" + res.Key + " occurence:" + res.Value.ToString());
}
Console.Read();
}
该算法包括两个阶段。
使用正则表达式进行模式匹配。还有其他更先进的算法。这些算法已在地址http://www-igm.univ-mlv.fr/~lecroq/string/上登记 但是,代码示例是用C语言编写的。另外,您可以查看Boyer-Moore algorithm的模式匹配,用C#编写
答案 1 :(得分:1)
伪代码:
For N=1 to InputString.Length-1
rotatedString = RotateStringByN(InputString,N)
For N=0 to InputString.Length-1
StringResult[N] = if (rotatedString[N]==InputString[N]) then
InputString[N]
else
Convert.ToChar(0x0).ToString()
RepeatedStrings[] = String.Split(StringResult, Convert.ToChar(0x0).ToString())
SaveLongestStringFrom(RepeatedStrings)
...或者只是在SO thread查看其他解决方案。