gpt4 book ai didi

c# - 字符重复

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:47:28 27 4
gpt4 key购买 nike

我正在编写一个简单的程序来计算字符串序列中字符的重复次数。我现在的程序如下,但我想看看它是否可以进一步优化。我相信现在的程序是 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 实现这一点。但这不是我要找的东西。感谢您的帮助。

最佳答案

不确定我是否正确阅读了问题,但这在您的情况下是否可行

    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);
}
}

关于c# - 字符重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14915626/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com