Leetcode:3. Longest Substring Without Repeating Characters

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.


很简单的一道题,我用hashmap做的将每个字符的位置存入hash表中,如果有重复的字符已经在表中时更新t_start,t_end ,将hash表置空然后继续遍历字串s 每次更新最长时的状态和index.然后返回就ok了~

int hash_map[128]={0};
int lengthOfLongestSubstring(char* s) {
    memset(hash_map,0, sizeof(hash_map));
    int i=0;
    int start=0;
    int end = 0;
    int t_start,t_end;
    int key = 0;
    int length=0;
    int t_length=0;
    t_start=0;
    t_end=-1;
    while (s[i]!='\0') {
        key = (int)s[i];
        if(hash_map[key] == 0)
        {
            hash_map[key] = i+1;
            t_end++;
            t_length = t_end - t_start+1;

        }
        else
        {   int temp = t_start;
            t_start = hash_map[key]-1+1;

            t_end = i;
            t_length = 1;
            for (int j = temp; j < t_start; j++) {
                hash_map[(int)s[j]] = 0;
            }
             hash_map[key] = i+1;

        }
        if(t_length>length)
        {
            start = t_start;
            end = t_end;
            length = t_length;

        }
        i++;
    }
    return length;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值