码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 3: Longest Substring Without Repeating Characters

时间:2017-11-04 13:35:47      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:pre   sub   out   remove   solution   log   blog   sequence   ret   

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.

 

 1 public class Solution {
 2     public int LengthOfLongestSubstring(string s) {
 3         int i = 0, j = 0, curMax = 0;
 4         
 5         var dict = new Dictionary<char, int>();
 6         
 7         while (j < s.Length)
 8         {
 9             if (dict.ContainsKey(s[j]))
10             {
11                 var index = dict[s[j]];
12                 while (i <= index)
13                 {
14                     dict.Remove(s[i]);
15                     i++;
16                 }                            
17             }
18             else
19             {
20                 curMax = Math.Max(curMax, j - i + 1);
21             }
22             
23             dict[s[j]] = j;
24             j++;
25         }
26         
27         return curMax;
28     }
29 }

Leetcode 3: Longest Substring Without Repeating Characters

标签:pre   sub   out   remove   solution   log   blog   sequence   ret   

原文地址:http://www.cnblogs.com/liangmou/p/7782961.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!