Skip to content

Instantly share code, notes, and snippets.

@DmitriiKh
Created August 24, 2020 23:22
Show Gist options
  • Save DmitriiKh/2ab7e72731d15ae1014746dc0312cb2d to your computer and use it in GitHub Desktop.
Save DmitriiKh/2ab7e72731d15ae1014746dc0312cb2d to your computer and use it in GitHub Desktop.
Longest Substring Without Repeating Characters
public class Solution
{
public int LengthOfLongestSubstring(string s)
{
var given = s.ToCharArray();
var charsPositions = new Dictionary<char, int>();
int startPosition = 0, maxLength = 0;
for (var endPosition = 0; endPosition < given.Count(); endPosition++)
{
var ch = given[endPosition];
if (!charsPositions.ContainsKey(ch))
{
charsPositions.Add(ch, endPosition);
maxLength = Math.Max(maxLength, charsPositions.Count);
}
else
{
var prevCharPosition = charsPositions[ch];
foreach (var charToRemove in given[startPosition..prevCharPosition])
{
charsPositions.Remove(charToRemove);
}
charsPositions[ch] = endPosition;
startPosition = prevCharPosition + 1;
}
}
return maxLength;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment