3.Longest Substring Without Repeating Characters

来源:互联网 发布:云软件官方下载 编辑:程序博客网 时间:2024/06/07 18:16
#define ASCII_NUM 128   //String可能包含128个asciitypedef struct Node{    int num;    struct Node* next;}Node, *pNode;int lengthOfLongestSubstring(char* s) {    /************************尾插法建立哈希表***************/    pNode arr[ASCII_NUM] = {NULL};    for (int i = 0; i < ASCII_NUM; i++)    {        arr[i] = (pNode)malloc(sizeof(Node));        arr[i]->num = 0;        arr[i]->next = NULL;    }    for (int i = 0; i < strlen(s); i++)    {        int num = s[i];        pNode p = (pNode)malloc(sizeof(Node));        p->num = i;        p->next = arr[num]->next;        arr[num]->next = p;    }    /*********************************************************/    bool bflag[ASCII_NUM] = {false};    int begin = 0;    int lenth = 0;    int maxLenth = 0;    int maxBegin = 0;    for (int i = 0; i < strlen(s); i++)    {        int num = s[i];        if (bflag[num] == false)        {            bflag[num] = true;            lenth++;            if (maxLenth < lenth)   //此部分不能放else里            {                maxLenth = lenth;                maxBegin = begin;            }        }        else        {            pNode q = (pNode)malloc(sizeof(Node));            q = arr[num]->next;            while (i != q->num)     //找到重复的字符            {                q = q->next;            }            while (begin < q->next->num)    //此部分必须跟新            {                bflag[s[begin]] = false;                begin++;            }            begin = q->next->num + 1;            lenth = i - q->next->num;        }    }    return maxLenth;}
0 0