[Leetcode]3. Longest Substring Without Repeating Characters

本文探讨了一种利用动态规划和哈希表解决寻找字符串中最长无重复字符子串问题的算法。介绍了两种方法:一种时间复杂度为O(n^2)但内存占用较少;另一种时间复杂度为O(n),虽然内存占用较多,但效率更高。文章详细阐述了算法的实现过程,并提供了关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Proble description:
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.

[Dynamic Programming] [Hashtable]

元旦刷了这题,算较复杂的dp题因为牵涉到hashtable。
开始使用O(n^2)但少用内存的方法被判定超时
后来用O(n)但多用了2KB的方法通过了

题目中保换的数据结构
int placeholder[256]; //用来存储当前最长连续非重复字符串,1表示在其中,0表示不在其中
int tailHolder[256]; //用来存储当前尾部最长连续非重复字符串, 也是0、1标示
int tailIndex[256]; //用来存储当前尾部最长连续非重复字符串中各个char在串中的index,从1开始
int maxLetter[length]; //length为输入string的长度,它用来存储长度从1~length的substring中最长连续非重复字符串的长度
int isTailed; //表明当前最长连续非重复字符串是否是尾部的substring
int tail_max;

Linear scan the string s
And parse every character s[i]

[1].check the isTailed
    [1.1]True! check (tailHolder[s[i]]==1)?
        [1.1.1]True!
            updateTailHolder();
            updatePlaceHolder();
            tail_max = tail_max - tailIndex[s[i]] + 1;
            updateIndex(tail_max_string);
            isTailed = 0;
        [1.1.2]False!
            tail_max++;
            tailIndex[s[i]] = tail_max;
            placeHolder[s[i]] = 1;
            tailHolder[s[i]] = 1;
    [1.2].False! check (tailHolder[s[i]]==1)?
        [1.2.1]True!
            updateTailHolder();
            updatePlaceHolder();
            tail_max = tail_max - tailIndex[s[i]] + 1;
            updateIndex(tail_max_string);
        [1.2.2]False! Check (tail_max+1==maxLetter[i-1])?
            [1.2.2.1]True
                tailHolder[s[i]] = 1;
                assign(placeHolder, tailHolder);
                tail_max++;
                tailIndex[s[i]] = tail_max;
            [1.2.2.2]False
                tailHolder[s[i]] = 1;
                tail_max++;
                tailIndex[s[i]] = tail_max;
    END
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值