Featured image of post 3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

最长的无重复字符子串

  给定一个字符串 $s$,返回其中不含有重复字符的最长子串的长度。 例1:

输入: s = "abcabcbb"
输出: 3

例2:

输入: s = "bbbbb"
输出: 1

例3:

输入: s = "pwwkew"
输出: 3

约束条件:

$$\begin{aligned} 0 <= s.length <= 5*10^4 \end{aligned}$$

\(s\) 由英文字母、数字、符号和空格组成


一上来,就容易想到的解法,但是比较耗内存:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <string.h>
int lengthOfLongestSubstring(char *s)
{
    char bin[256] = {0};
    unsigned short length = strlen(s);
    unsigned short ret = 0, this_ret = 0;

    for (int i = 0; i < length; i++)
    {
        if (bin[s[i]] != 0)
        {
            if (s[i - this_ret] == s[i])
                continue;
            if (ret < this_ret)
                ret = this_ret;
            while (s[i - this_ret] != s[i]){
                bin[s[i-this_ret]] = 0;
                this_ret --;
            }
        }else{
            bin[s[i]] = 1;
            this_ret++;
        }
    }

    return ret<this_ret?this_ret:ret;
}
C


提交截图(提交时,非现在状态)


完整信息点击此连接查看

Licensed under CC BY-NC-SA 4.0
最后更新于 Aug 17, 2024 23:15 +0800

请在评论前阅读我们的评论政策


内容是由智能博客生成器生产 powered by ChatGGPTT
使用 Hugo 构建
主题 StackedJimmy 设计,Jacob 修改