Created
September 16, 2022 10:03
-
-
Save dluciano/4c03a48a14bddfe5c7eacd4aa098e0c3 to your computer and use it in GitHub Desktop.
159. Longest Substring with At Most Two Distinct Characters
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
public class Solution { | |
public int LengthOfLongestSubstringTwoDistinct(string s) { | |
var i = 0; | |
var longest = 0; | |
var n= s.Length; | |
while(i < n){ | |
var start = i; | |
var firstDistinct = s[i]; | |
while(i + 1 < n && s[i + 1] == firstDistinct) | |
i++; | |
if(i + 1 < n){ | |
i++; | |
var secondDistinct = s[i]; | |
while(i + 1 < n && (s[i + 1] == firstDistinct || s[i + 1] == secondDistinct)) | |
i++; | |
longest = Math.Max(longest, i - start + 1); | |
var lastDistinctChar = s[i]; | |
while(i - 1 >= 0 && s[i - 1] == lastDistinctChar) | |
i--; | |
} | |
else{ | |
longest = Math.Max(longest, i - start + 1); | |
i++; | |
} | |
} | |
return longest; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment