3. Longest Substring Without Repeating Characters
Posted HenRy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3. Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。
Difficulty: Medium
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given
"abcabcbb"
, the answer is"abc"
, which the length is 3.Given
"bbbbb"
, the answer is"b"
, with the length of 1.Given
"pwwkew"
, the answer is"wke"
, with the length of 3. Note that the answer must be a substring,"pwke"
is a subsequence and not a substring.
选出一个不含重复字符连续的子字符串,我们最先想到的办法是得出所有的不含连续字符的子字符串然后选出其中长度最长的那一个,循环整个字符串,然后将字符存进一个新的数组,当碰到有重复的时候,算出此时新数组的长度并去掉这个与之相同的字符及他之前加进来的字符,再往后循环,直至结束。
下面用的是字典来存储元素,循环字符串,立标志位来标志上次开始计数的index,于是长度为 i- flag+1,由于这个判断在往里面加元素之前,所以加元素的时候为i+1。
假如length=2,result=1 -> dic0为[a,1] ->result=2->dic1 [b,2]->loop end 。
假如dic中包含现在的a[i],那么flag就赋值为之前等于a[i]的index+1,再去掉之前那个等于a[i]的元素,dic只是用来标记。
My submission Runtime:168ms(longer than expected)
1 public int LengthOfLongestSubstring(string s) 2 { 3 char[] array = s.ToCharArray(); 4 int length = array.Length; 5 int result = 0; 6 Dictionary<char, int> dic = new Dictionary<char, int>(); 7 int flag = 0; 8 for (int i = 0; i < length; i++) 9 { 10 if (dic.ContainsKey(array[i])) 11 { 12 flag = Math.Max(dic[array[i]], flag); 13 dic.Remove(array[i]); 14 } 15 result = Math.Max(result, i - flag + 1); 16 dic.Add(array[i],i+1); 17 } 18 19 return result; 20 21 }
复杂度:循环length次,O(n),时间复杂度 dic最大等于length个元素,于是O(n)。
ps:可以用一个128甚至更小的数组来代替dic来做标记,A=65,Z=90,a=97,z=122,123大小的数组也可以。array[c.ASCII]用来做标识位即可。
以上是关于3. Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章
longest-substring-with-at-least-k-repeating-characters
LeetCode 395. Longest Substring with At Least K Repeating Characters
395. Longest Substring with At Least K Repeating Characters
3. Longest Substring Without Repeating Characters
Leetcode: Longest Substring with At Least K Repeating Characters