1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

#include <iostream>
#include <string>

using namespace std;

#define MAX_CHARS 256

int LengthOfLongestSubstring(string s) 
{
    //indicate the index of postion of the character in the string
    int chars[MAX_CHARS];
    for (int i = 0; i < MAX_CHARS; ++i)
        chars[i] = -1;

    int longest = 0;
    int start = 0;
    int sLength = s.size();
    for (int i = 0; i < s.size(); ++i)
    {
        //the character has been used
        if (chars[s[i]] >= 0)
        {
            int len = i - start;
            if (longest < len) longest = len;
            
            //set all characters, which are from previous start to the 
            //repeated one, as unused
            while(start <= chars[s[i]])
                chars[s[start++]] = -1;
        }

        //save the position in the string,
        //also indicate the character has been used
        chars[s[i]] = i;
    }

    int len = sLength - start;
    if (longest < len)longest = len;

    return longest;
}

int main(int argc, char** argv)
{
    string s = "abc";
    cout << s << ": " <<LengthOfLongestSubstring(s) << endl;

    s = "abcdefghhaijklmn";
    cout << s << ": " <<LengthOfLongestSubstring(s) << endl;

    s = "aaaaaaaaaaaa";
    cout << s << ": " <<LengthOfLongestSubstring(s) << endl;

    return 0;
}
View Program Text


Test Status