Se la stringa è breve, solo il looping e il test potrebbero essere il modo più semplice ed efficace. Voglio dire che tu potresti creare un set di hash (in qualunque piattaforma tu stia usando) e scorrere tra i personaggi, fallendo se il personaggio è già nel set e aggiungendolo al set in altro modo - ma è probabile che fornisca qualche beneficio quando le corde sono più lunghe
EDIT: Ora che sappiamo che è ordinato, mquander's answer è il migliore IMO. Ecco un'implementazione:
public static bool IsSortedNoRepeats(string text)
{
if (text.Length == 0)
{
return true;
}
char current = text[0];
for (int i=1; i < text.Length; i++)
{
char next = text[i];
if (next <= current)
{
return false;
}
current = next;
}
return true;
}
A breve alternativa, se non ti dispiace ripetere l'uso indicizzatore:
public static bool IsSortedNoRepeats(string text)
{
for (int i=1; i < text.Length; i++)
{
if (text[i] <= text[i-1])
{
return false;
}
}
return true;
}
EDIT: Okay, con il lato "frequenza", mi trasformerò il problema rotonda un po. Devo ancora supporre che la stringa sia ordinata, quindi quello che vogliamo sapere è la lunghezza della corsa più lunga. Quando non ci sono ripetizioni, la lunghezza della corsa più lunga sarà 0 (per una stringa vuota) o 1 (per una stringa non vuota). Altrimenti, saranno 2 o più.
Prima una versione specifica stringa:
public static int LongestRun(string text)
{
if (text.Length == 0)
{
return 0;
}
char current = text[0];
int currentRun = 1;
int bestRun = 0;
for (int i=1; i < text.Length; i++)
{
if (current != text[i])
{
bestRun = Math.Max(currentRun, bestRun);
currentRun = 0;
current = text[i];
}
currentRun++;
}
// It's possible that the final run is the best one
return Math.Max(currentRun, bestRun);
}
Ora possiamo anche fare questo come un metodo di estensione generale sulla IEnumerable<T>
:
public static int LongestRun(this IEnumerable<T> source)
{
bool first = true;
T current = default(T);
int currentRun = 0;
int bestRun = 0;
foreach (T element in source)
{
if (first || !EqualityComparer<T>.Default(element, current))
{
first = false;
bestRun = Math.Max(currentRun, bestRun);
currentRun = 0;
current = element;
}
}
// It's possible that the final run is the best one
return Math.Max(currentRun, bestRun);
}
Quindi è possibile chiamare "AABCD".LongestRun()
per esempio.
"ABCDA" dovrebbe essere considerato come ripetuto? Cioè sei interessato a eventuali ripetizioni o solo a caratteri consecutivi? – Richard
Quale versione del framework? – BenAlabaster
La versione del framework è 3.5 – inspite