Leetcode 3: Longest Substring Without Repeating Characters

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 3: Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 3. Longest Substring Without Repeating Characters

LeetCode 3. Longest Substring Without Repeating

3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]

3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]

leetcode longest consecutive sequence

leetcode 3. Longest Substring Without Repeating Characters (Python版)