Leetcode Q3:Longest Substring Without Repeating Characters

来源:互联网 发布:sql查询每小时 编辑:程序博客网 时间:2024/06/03 21:05

题目3:

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.

#define MAP_SIZE    256 int lengthOfLongestSubstring(char* s) {    int i = 0;    int start = 0;          char* p = NULL;    int temp_max_size = 0;              /* 当次找到的最大子串长度 */    int max_size = 0;           static int MapRecord[MAP_SIZE];    /* 如果将这两个数组放在全局变量中,在leetcode上就会报错 */        memset(MapRecord, -1, MAP_SIZE*sizeof(int));    p = s;    start = 0;                      /* 记录当前查询到的最长子串的起始位置 */    while (*p != '\0')    {        if (MapRecord[*p] == -1)        {            MapRecord[*p] = p - s;      /* map记录已经在子串中 */            temp_max_size++;            p++;        }        else                        /* 遇到相同的字符 */        {            /* 当前查找到的最大子串中,清空相同字符前的map,子串从相同字符串位置后一个开始记录  */            for (i = start; i < MapRecord[*p]; i++)            {                MapRecord[*(s+i)] = -1;              }            if (temp_max_size > max_size)            {                max_size = temp_max_size;            }            temp_max_size -= (MapRecord[*p] - start);            start = MapRecord[*p] + 1;     /* 修改当前最大子串的开始位置 */            MapRecord[*p] = p - s;            p++;        }    }    /* 字符串结束时,输出结果 */    if (temp_max_size > max_size)    {        max_size = temp_max_size;    }    return max_size;}

0 0
原创粉丝点击