문자열이 짧으면 루핑과 테스트가 가장 간단하고 효율적인 방법 일 수 있습니다. 내 말은 당신이 일 수있다. 해시 세트를 만들고 (사용중인 플랫폼에 관계없이) 캐릭터를 반복하며, 캐릭터가 이미 세트에 포함되어 있고 그렇지 않은 경우 세트에 추가하면 실패한다. 그러나 이것은 모든 이점을 제공 할 가능성이있다. 문자열이 더 길 때.
편집 : 이제 알 수 있듯이 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()
를 호출 할 수 있습니다.
"ABCDA"는 반복되는 것으로 취급됩니까? 나는. 반복 또는 연속 된 문자에만 관심이 있으십니까? – Richard
프레임 워크의 어떤 버전입니까? – BenAlabaster
프레임 워크 버전은 3.5입니다. – inspite