[LeetCode打卡] 最长无重复子串

本文记录了LeetCode中关于找到字符串中最长无重复子串的解题过程,包括题目描述、运行结果展示及个人解答思路。
摘要由CSDN通过智能技术生成

题目

在这里插入图片描述

运行结果

在这里插入图片描述
在这里插入图片描述

我的解答

#include<iostream>
#include<unordered_map>
using namespace std;

struct SectInfo
{
    int startIndex;
    int endIndex;
            
    int Size() {
        return endIndex - startIndex + 1;
    }
    SectInfo(int index, string& src):src(src),startIndex(index),endIndex(index)
    {
        charMap.insert(pair<char, int>(src[index], index));
    }

    bool AdaptNext()
    {
        auto newEnd = endIndex + 1;
        if (newEnd == src.length())
            return false;
        auto newChar = src[newEnd];
        if (ContainsChar(newChar))
        {
            auto existPos = charMap.at(newChar);
            for (auto i = startIndex; i < existPos; i++)
            {
                charMap.erase(src[i]);
            }
            startIndex = existPos+1;
        }
        else
        {
            charMap.insert(pair<char, int>(newChar, -1));
        }
        charMap.at(newChar) = newEnd;
        endIndex = newEnd;
        return true;
    }
    bool ContainsChar(char ch)
    {
        return charMap.count(ch);
    }
private:
    const string& src;
    unordered_map<char, int> charMap;
};


class Solution {
public:
    int lengthOfLongestSubstring(string s) {

        if (s.length() == 0)
            return 0;
        SectInfo sect(0, s);
        int startIndex = 0, endIndex = 0, maxSize = 0;
        while(true)
        {
            if (sect.Size() > maxSize)
            {
                startIndex = sect.startIndex;
                endIndex = sect.endIndex;
                maxSize = sect.Size();
            }
            if (!sect.AdaptNext())
            {
                break;
            }
        }
        auto ans = s.substr(startIndex, maxSize);
        return maxSize;
    }
};

int main()
{
    string s;
    Solution solution;
    while (true)
    {
        cin >> s;
        cout<<solution.lengthOfLongestSubstring(s)<<endl;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值