Longest Substring Without Repeating Characters

本文介绍了一种算法,用于在给定字符串中找到最长的子串,其中每个字符只出现一次。通过使用一个数组记录字符的位置,该算法能够高效地解决此问题。

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

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.

题意在原串中找到最长的每个字母最多出现一次的字符串

用一个sign[256]来记录出现过的字符位置,偷懒点用265可以处理一个ASCII表。
遇到没有出现过的字符,将sign对应位置标记-1。
遇到出现过的字符,出现该字符上次出现位置前面截断(即赋值为-1),调整长度。

#include<iostream>
#include <algorithm>
#include<cstring>
using namespace std;
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int start = 0;
        int movep = 0;
        int sign[256];
        int mmax = 0;
        int templen = 0;
        int curStart = 0;
        int lastSi = 0;
        memset(sign,-1,sizeof(sign));   //注意mem第三个参数,类型是size_t
        for(;movep<s.size();movep++)
        {
            char si = s[movep];
            lastSi = sign[si];
            if( sign[si] == -1)
            {
                templen++;
                sign[si] = movep;
            }
            else
            {
                //删除前面重复的,重新调整长度
                curStart = movep - templen;
                for(int j = curStart; j < lastSi; ++j) {
                    sign[s[j]] = -1;
                }
                templen = movep - lastSi;
                sign[si] = movep;
            }
            mmax = max(mmax,templen);
        }

        return mmax;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值