LeetCode 3. Longest Substring Without Repeating Characters

本文介绍了一种解决最长无重复字符子串问题的有效算法。通过遍历字符串并使用数组记录字符位置,该算法能够找到最长的不包含重复字符的子串长度。支持多种编程语言实现,包括C/C++、Java及Python。

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

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

解题思路:题中所描述的字符包括所有128个ASCII字符,定义一个数组alph记录每个字符出现的位置,并且用一个变量mark记录当前子串起点的位置,变量maxlen记录当前最长的子串的长度,字符的位置随着循环不断往后进行更新,如果出现字符的上一个位置在当前子串起点之后,更新起点的位置为当前字符上一个位置的后一位作为起点,同时判断是否需要更新maxlen。

C/C++

int lengthOfLongestSubstring(char* s) {
    int i = -1;
    int alph[128] = {0};
    for(int i=0;i<128;i++)alph[i]=-1;
    int mark = -1;
    int maxlen = 0;
    while(s[i+1])
    {
        i++;
        int tmp = s[i];
        if(alph[tmp]>mark)
        {
            if(maxlen<i-mark-1)maxlen=i-mark-1;
            mark = alph[tmp];
        }
        alph[tmp] = i;
    }
    if(maxlen<i-mark)maxlen=i-mark;
    return maxlen;
}

Java

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] alph = new int[128];
        for(int i=0;i<128;i++)alph[i]=-1;
        int i = -1;
        int mark = -1;
        int maxlen = 0;
        while(i+1<s.length()) {
            i++;
            int tmp = s.charAt(i);
            if(alph[tmp]>mark) {
                if(maxlen<i-mark-1)maxlen=i-mark-1;
                mark = alph[tmp];
            }
            alph[tmp] = i;
        }
        if(maxlen<i-mark)maxlen=i-mark;
        return maxlen;
    }
}

Python

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        alph = []
        for i in range(128):alph.append(-1)
        i = -1
        mark = -1
        maxlen = 0
        while i+1<len(s):
            i += 1
            tmp = ord(s[i])#字符转整型要用函数,不可直接赋值
            if alph[tmp]>mark:
                if maxlen<i-mark-1:maxlen=i-mark-1
                mark = alph[tmp]
            alph[tmp] = i;
        if maxlen<i-mark:maxlen=i-mark
        return maxlen

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值