Longest Substring Without Repeating Characters @leetcode

本文详细介绍了如何通过滑动窗口和使用哈希集合的方法解决 LeetCode 上的「最长无重复字符子串」问题,并提供了源代码实现。文中包括对关键步骤的解释和代码示例。

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

原题链接: http://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ 

链接:http://blog.youkuaiyun.com/linhuanmars/article/details/19949159 给出了比较详细的分析,同时也给出了一个需要一hashset的线性是时间方法。

这道题目,我做的时候,采用的同样是窗口的思想,利用一个浮动的窗口,来判断是否有重复的字符。 如何判断是否有重复的字符,用一个260的char数组来表示当前窗口里面所有出现的字符的数量。然后判断start-end这一个区间里面,是否出现了重复字符,如果有重复字符,那么调整start的位置,直到消除重复字符,如此反复,就能够知道最长的区间是多少了。

源代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int text[256] = {0};
        int isz = s.length();
        int mmax = 0;
        int count = 0;
        int start = 0 ;
        int end = 0;
        while (end < isz)
        {
            text[s[end]] ++;
            count ++;
            if(text[s[end]] >1 )
            {
                //cout << count << endl;
                mmax = mmax > count-1? mmax : count-1;
                while (text[s[end]] > 1)
                {
                    text[s[start]] --;
                    start ++;
                    count --;
                }
                //cout <<start << " " <<  count <<endl;
            }
            end ++;
        }
        mmax = mmax > count? mmax : count;
        return mmax;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值