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]用来做标识位即可。

 

转载于:https://www.cnblogs.com/leakeyash/p/5618731.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值