我正在寫一個簡單的程序來計算字符串序列中字符的重複。我現在的程序如下,但我期待看看它是否可以進一步優化。我相信現在的程序是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來實現這一點。但那不是我正在尋找的東西。感謝你的幫助。
它必須是'O(n)',因爲必須經過每個角色。我不明白你甚至可以從理論上減少這種情況。 – Oded 2013-02-16 22:06:33
只有這個代碼看起來高於O(n)..?但我不知道如何改進這個想法。 – 2013-02-16 22:09:46
@Cicada你能讓我知道我能做些什麼來改善這個代碼嗎?是的,我可以理解O(n)運行時間背後的邏輯。 – 2013-02-16 22:23:43