Hi!
LeetCode 第三道题: Longest Substring Without Repeating Characters,难度中等。
Given a string, find the length of the longest substring without repeating characters. Example 1: Input: “abcabcbb” Output: 3 Explanation: The answer is “abc”, with the length of 3.
Example 2: Input: “bbbbb” Output: 1 Explanation: The answer is “b”, with the length of 1.
Example 3: Input: “pwwkew” Output: 3 Explanation: 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 int LengthOfLongestSubstring(string s)
2 {
3 var maxLength = 0;
4 var start = 0;
5 var length = 0;
6 var dict = new Dictionary<string, int>();
7 for (int i = 0; i < s.Length; i++)
8 {
9 var cs = s[i].ToString();
10 if (dict.ContainsKey(cs))
11 {
12 if (dict[cs] >= start)
13 {
14 length = length - (dict[cs] - start + 1);
15 start = dict[cs] + 1;
16 }
17
18 dict[cs] = i;
19 }
20 else
21 {
22 dict.Add(cs, i);
23 }
24
25 length++;
26
27 if (maxLength < length)
28 {
29 maxLength = length;
30 }
31
32 }
33
34 return maxLength;
35 }
To use, see:Jektify - Doc
Goodbye!
Put a very powerful message.