Problem
Given a string s
, find the length of the longest
substring without repeating characters.
Example 1:
Input: s = “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: s = “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: s = “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3. Notice that the answer must be a substring, “pwke” is a subsequence and not a substring.
Constraints:
0 <= s.length <= 5 * 104
s
consists of English letters, digits, symbols and spaces.
Solution
public int LengthOfLongestSubstring(string s) {
var longest = 0;
var start = 0; // searching for sequence from
for (var i = 0; i < s.Length; i++) {
// Find the index of current i character from start till next i-start characters.
// e.g. defabcab
// In above example 'a' is repeated in first unique sequence (defabc) at index 6.
// So we know for sure that next non repeating sequence could start from 4th index.
// What we do is, first we find the occurance of current ith character in from start till i
// If we find don't find one then we check if sequence is longer. If yes, then we update the longest
// and if find the ith character to be repeated,
// then we start from next character of the repeating character in the current unique sequence
var indexOfCurrentChar = s.IndexOf(s[i], start, i - start);
if (indexOfCurrentChar == -1) {
if (longest < i - start + 1) {
longest = i - start + 1;
}
} else {
// next seq start would be from the next character which is repeated
start = indexOfCurrentChar + 1;
}
}
return longest;
}