문자열 시퀀스에서 문자의 반복을 계산하는 간단한 프로그램을 작성하고 있습니다. 지금 가지고있는 프로그램은 아래와 같습니다.하지만 더 이상 최적화 할 수 있는지보고 싶습니다. 나는 프로그램이 지금 최악 (O) 최악의 경우라고 생각하며, 실행 시간을 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에서도 얻을 수 있다는 것을 알고있다. 그러나 그것은 내가 찾고있는 것이 아닙니다. 당신의 도움을 주셔서 감사합니다. 내가 제대로 질문을 읽을 수 있지만이 작업을 다른 문자의 수를 알고있는 경우 상황
public void FindCharRepetitions(string toCheck)
{
var result = new Dictionary<char, int>();
foreach (var chr in toCheck)
{
if (result.ContainsKey(chr))
{
result[chr]++;
continue;
}
result.Add(chr, 1);
}
foreach (var item in result)
{
Console.WriteLine("Char: {0}, Count: {1}", item.Key, item.Value);
}
}
각각의 문자를 통과해야하므로 _has_는 'O (n)'이됩니다. 나는 이론적으로 그것을 줄일 수있는 방법을 모르겠다. – Oded
이 코드는 O (n)보다 약간 위의 코드입니다.? 그러나 나는 그 생각을 세련시키는 법을 모른다. –
@ Cicada이 코드를 개선하기 위해 내가 할 수있는 일을 알려 주실 수 있습니까? 예, O (n) 실행 시간 뒤에있는 논리를 이해할 수 있습니다. –