Last active
April 12, 2022 13:23
-
-
Save dmdeluca/e2c8a17f807971713e5062d419cbd70f to your computer and use it in GitHub Desktop.
A solution to the longest substring problem using HashSet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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