3. Longest Substring Without Repeating Characters (ASCII码128个,建立哈西表)

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.

int lengthOfLongestSubstring(char* s) {
    int latestPos[128]; //map<char,int>
    int result = 0;
    int i = 1;
    int startPos = 0;

    if(strcmp(s,"")==0) return result;
    
    memset(latestPos, -1, sizeof(latestPos));
    latestPos[s[0]] = 0;
    while(s[i]!='\0'){
        if(latestPos[s[i]] >= startPos){ //s[i] already appeared
            if(i-startPos > result) result = i-startPos;
            startPos = latestPos[s[i]]+1;
        }
        latestPos[s[i]] = i;
        i++;
    }
    if(i-startPos > result) result = i-startPos;
    return result;
}

 

posted on 2016-03-13 11:00  joannae  阅读(207)  评论(0编辑  收藏  举报

导航