given a string s, find the length of the longest substring that has no repeated characters in csharp

One approach to solve this problem is by using a sliding window technique along with a hash set to keep track of the characters that have been seen before.

Here's how it can be implemented in C#:

main.cs
public int LengthOfLongestSubstring(string s) {
    int n = s.Length;
    HashSet<char> set = new HashSet<char>();
    int maxLength = 0, i = 0, j = 0;
    
    while (i < n && j < n) {
        if (!set.Contains(s[j])) {
            // if the character hasn't been seen before, add it to the set and expand the window
            set.Add(s[j++]);
            maxLength = Math.Max(maxLength, j - i);
        } else {
            // if the character has been seen before, remove it from the set and contract the window
            set.Remove(s[i++]);
        }
    }
    
    return maxLength;
}
594 chars
19 lines

In this code, i and j are the start and end indices of the sliding window respectively. The variable set is used to store the characters that have been seen before. We start with an empty set and move the window to the right until we find a repeated character. At each step, we update the maxLength with the current length of the window. If a repeated character is found, we remove the starting character from the set and move the window to the right.

gistlibby LogSnag