LeetCode Online Judge 题目C# 练习 - Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

 

 1         public static int LongestSubstringWithoutRepeatingCharacters(string s)
 2         {
 3             //ASCII has 256 characters
 4             BitArray map = new BitArray(256, false);
 5             int i = 0, j = 0;
 6             int max = 0;
 7             int n = s.Length;
 8 
 9             while(j < n)
10             {
11                 if (map[s[j]])
12                 {
13                     max = Math.Max(max, j - i);
14                     //remove all the pervious character from map before duplicate
15                     while(s[i] != s[j])
16                     {
17                         map[s[i]] = false;
18                         i++;
19                     }
20                     i++;
21                     j++;
22                 }
23                 else
24                 {
25                     map[s[j]] = true;
26                     j++;
27                 }
28             }
29 
30             max = Math.Max(max, j - i);
31 
32             return max;
33         }

代码分析:

  用一个BitArray来存放出现过的字符。时间复杂度O(n)。

  j 指针往前走,并mark下出现的字符,一旦发现重复,i 往前走,走到与 j 位置相同的字符处, 并wipe out出现的字符。

  例如:"abcabcbb", 

  "a b c a b c b b"  "a b c a b c b b"  "a b c a b c b b"  "a b c a b c b b"  "a b c a b c b b"  "a b c a b c b b"

   i          i            i               i            i               i

   j                   j                j            j               j            j

            max = 3 ("abc")    "bca"        "cab"        "abc"        "cb"       

                     

posted @ 2012-09-21 04:09  ETCOW  阅读(399)  评论(0编辑  收藏  举报