LeetCode-3:Longest Substring Without Repeating Characters

本文介绍LeetCode中等难度题目——最长无重复字符子串的两种解题思路及其实现代码。一种使用Bitmap进行统计,另一种通过数组记录字符位置。

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

一、题目

原题链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/
难度等级:中等

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.

题目翻译:
给定一个字符串,找出其中无重复字符的最长子串的长度。
例如:
“abcabcbb”,无重复字符的最长子串是”abc”,长度为3。
“bbbbb”,无重复字符的最长子串是”b”,长度为1


二、解题方案

思路1:
通过Bitmap来统计是否子字符串中有重复的字符。遍历时若遇到重复值,需要回溯。

代码实现:

class Sulution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char, int> m;
        int maxLen = 0;
        int lastRepeatPos = -1;
        for (int i = 0; i < s.size(); ++i) {
            if (m.find(s[i]) != m.end() && lastRepeatPos < m[s[i]]) {
                lastRepeatPos = m[s[i]];
            }
            if (i - lastRepeatPos > maxLen) {
                maxLen = i -lastRepeatPos;
            }
            m[s[i]] = i;
        }

        return maxLen;
    }
};

思路2:
通过一个数字来存储每一个字符上一次出现的位置,当出现冲突时及时调整。

代码实现:

class Sulution {
public:
    int lengthOfLongestSubstring(string s) {
        const int MAX_CHARS = 256;
        int m[MAX_CHARS];
        memset(m, -1, sizeof(m));

        int maxLen = 0;
        int lastRepeatPos = -1;
        for (int i = 0; i < s.size(); ++i) {
            if (m[s[i]] != -1 && lastRepeatPos < m[s[i]]) {
                lastRepeatPos = m[s[i]];
            }
            if (i - lastRepeatPos > maxLen) {
                maxLen = i -lastRepeatPos;
            }
            m[s[i]] = i;
        }

        return maxLen;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值