Skip to content

Instantly share code, notes, and snippets.

@dmdeluca
Last active April 12, 2022 13:23
Show Gist options
  • Save dmdeluca/e2c8a17f807971713e5062d419cbd70f to your computer and use it in GitHub Desktop.
Save dmdeluca/e2c8a17f807971713e5062d419cbd70f to your computer and use it in GitHub Desktop.
A solution to the longest substring problem using HashSet
namespace DSA {
public class LongestSubstringProblem {
public static string HashSetSolution(string input) {
if (string.IsNullOrEmpty(input))
return string.Empty;
var (candidateStart, candidateLength) = (0, 1);
var current = new HashSet<char>();
int start = 0;
foreach (var character in input) {
while (current.Contains(character)) {
current.Remove(input[start++]);
}
// Mark the character as present in the current substring.
current.Add(character);
if (candidateLength < current.Count) {
candidateStart = start;
candidateLength = current.Count;
}
}
return input.Substring(candidateStart, candidateLength);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment