如果字符串很短,那么循环和测试可能是最简单和最有效的方法。我的意思是您可以创建一个哈希集(在您使用的任何平台上)并遍历字符,如果字符已经在集合中则失败,否则将其添加到集合中 - 但这只是当字符串更长时可能会提供任何好处。
编辑:现在我们知道它已排序,mquander's answer 是最好的 IMO。这是一个实现:
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;
}
如果您不介意重复使用索引器,可以使用较短的替代方法:
public static bool IsSortedNoRepeats(string text)
{
for (int i=1; i < text.Length; i++)
{
if (text[i] <= text[i-1])
{
return false;
}
}
return true;
}
编辑:好的,在“频率”方面,我会稍微扭转一下这个问题。我仍然会假设字符串是排序的,所以我们想知道最长运行的长度。当没有重复时,最长的运行长度将为 0(对于空字符串)或 1(对于非空字符串)。否则,将是 2 个或更多。
首先是特定于字符串的版本:
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);
}
现在我们也可以将其作为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);
}
然后你可以打电话给"AABCD".LongestRun()例如。