1. 程式人生 > >Leetcode 3: Longest Substring Without Repeating Characters

Leetcode 3: Longest Substring Without Repeating Characters

max leetcode ans contain lee var ont sequence repeat

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