Created
August 24, 2020 23:22
-
-
Save DmitriiKh/2ab7e72731d15ae1014746dc0312cb2d to your computer and use it in GitHub Desktop.
Longest Substring Without Repeating Characters
This file contains hidden or 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
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