Last active
April 11, 2022 04:08
-
-
Save dmdeluca/3e09e0e9295a8fceedad6e34b11ab39b to your computer and use it in GitHub Desktop.
Simple solution to the longest non-repeating substring problem
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
using System.Runtime.CompilerServices; | |
namespace DSA { | |
public class LongestSubstringProblem { | |
/// <summary> | |
/// Solves the LongestSubstringProblem in O(N) time without any generic data structures or custom data structures. | |
/// </summary> | |
/// <param name="input"></param> | |
/// <returns></returns> | |
public static string SimpleBitMaskSolution(string input) { | |
if (string.IsNullOrEmpty(input)) | |
return string.Empty; | |
var candidateStart = 0; | |
var candidateLength = 1; | |
var mapMask = 0U; | |
var mapCount = 0; | |
int start = 0; | |
const char a = 'a'; | |
foreach (var character in input) { | |
var currentCharacterMask = 1U << (character - a); | |
while ((mapMask & currentCharacterMask) != 0) { | |
var startCharacterMask = 1U << (input[start] - a); | |
mapMask &= ~startCharacterMask; | |
mapCount--; | |
start++; | |
} | |
// Mark the character as present in the current substring. | |
mapMask |= currentCharacterMask; | |
mapCount++; | |
if (candidateLength < mapCount) { | |
candidateStart = start; | |
candidateLength = mapCount; | |
} | |
} | |
return input.Substring(candidateStart, candidateLength); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment