我正在编写一个简单的程序来计算字符串序列中字符的重复。我现在拥有的程序如下,但我希望看看它是否可以进一步优化。我相信现在的程序是 O(n) 最坏情况时间,我想看看是否有什么东西可以给我 O(log n) 运行时间。
using System;
using System.Collections.Generic;
namespace Algos
{
class CharacterRepitition
{
private char[] checkStringArray;
private bool[] discovered;
public CharacterRepitition(string toCheck)
{
checkStringArray= toCheck.ToCharArray();
discovered= new bool[checkStringArray.Length];
for (int i = 0; i < checkStringArray.Length; i++)
{
discovered[i] = false;
}
}
public void CheckRepetitions()
{
int charIndex=0;
Dictionary<char, int> repetitions = new Dictionary<char, int>();
while (charIndex < checkStringArray.Length)
{
int count = 0;
if(discovered[charIndex].Equals(false))
{
count = RunThroughTheString(charIndex, checkStringArray);
if (count > 0)
{
repetitions.Add(checkStringArray[charIndex], count+1);
}
}
charIndex++;
}
if (repetitions.Count == 0)
{
Console.WriteLine("\nNo characters repeated.");
}
else
{
foreach (KeyValuePair<char, int> result in repetitions)
{
Console.WriteLine("\n'"+ result.Key + "' is present: " + result.Value + " times.");
}
}
}
private int RunThroughTheString(int currentCharIndex, char[] checkStringArray)
{
int counter = 0;
for (int i = 0; i < checkStringArray.Length; i++)
{
if (checkStringArray[currentCharIndex].Equals(checkStringArray[i]) && i !=currentCharIndex)
{
counter++;
discovered[i] = true;
}
}
return counter;
}
}
}
我知道我也可以使用 LINQ 来实现这一点。但这不是我要找的东西。感谢你的帮助。