标签:
【题目描述】
Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
【解题思路】
1. 维护一个以start开始,end结束的窗口;
2. 利用HashSet来存储当前窗口的字符元素,以快速判断是否重复;
3. end先向后扫描,遇到重复的停止,并和当前的max比较大小,判断是否是当前的最大无重复子串;
4. start向后扫描,并从HashSet中移除所扫描的字符,直到和end指向字符相等的地方停止;
5. 重复34步骤,直到end扫描到字符串结尾,即可获取到最大无重复子串的长度;
BTW:由于start和end扫描的长度必然不大于字符串的长度,所以时间复杂度是O(n)+O(n)=O(n);
【代码实现】
1 public int LengthOfLongestSubstring(string s) 2 { 3 int start = 0, end = 0, max = 0; 4 HashSet<char> hs = new HashSet<char>(); 5 while (end < s.Length) 6 { 7 if (hs.Contains(s[end])) 8 { 9 max = Math.Max(max, end - start); 10 while (s[start] != s[end]) 11 { 12 hs.Remove(s[start]); 13 start++; 14 } 15 start++; 16 } 17 else 18 { 19 hs.Add(s[end]); 20 } 21 end++; 22 } 23 max = Math.Max(max, end - start); 24 return max; 25 }
3. Longest Substring Without Repeating Characters
标签:
原文地址:http://www.cnblogs.com/HuoAA/p/4790907.html