Leetcode Q3:Longest Substring Without Repeating Characters

题目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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值