【leetcode 03】【滑动窗口】

这是最开始写的错误版本,对于题目的具体问题理解不足。

cpp 复制代码
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.length();
        int left = 0, right = 1;
        int mmax = -1;
        unordered_set<int> uset;
        while ( right <= n - 1)
        {
            uset.insert(s[left]);
            if (uset.count(s[right]) > 0)
            {
                left++;
            }
            else
            {
                uset.insert(s[right]);
            }
            right++;
            mmax = max(mmax, (int)(uset.size()));
        }
        return mmax;
    }
};

加了n = 0和1时的特判。

leetcode对于max要求两个参数类型一致,卡的比较紧。

用了unordered_set复杂度是n^2logn,看来leetcode可以多用stl少考虑复杂度,先写最暴力的试试。

cpp 复制代码
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.length();
        if (n == 0) return 0;
        if (n == 1) return 1;
        int left = 0, right = 1;
        int mmax = 0;
        unordered_set<int> uset;
        
        while ( right <= n - 1)
        {
            uset.insert(s[left]);
            if (uset.count(s[right]) > 0)
            {
                while (s[left] != s[right])
                {
                    uset.erase(s[left]);
                    left++;
                }
                left++;
            }
            else
            {
                uset.insert(s[right]);
            }
            mmax = max(mmax, (int)(uset.size()));
            right++;
            
        }
        // if (mmax == 0) return 1;
        return mmax;
    }
};
相关推荐
努力努力再努力wz3 分钟前
【Linux进阶系列】:信号(下)
java·linux·运维·服务器·开发语言·数据结构·c++
TU^24 分钟前
C语言习题~day27
c语言·数据结构·算法
2401_8414956431 分钟前
【自然语言处理】Transformer模型
人工智能·python·深度学习·算法·语言模型·自然语言处理·transformer
孤廖33 分钟前
面试官问 Linux 编译调试?gcc 编译流程 + gdb 断点调试 + git 版本控制,连 Makefile 都标好了
linux·服务器·c++·人工智能·git·算法·github
404未精通的狗1 小时前
(数据结构)栈和队列
android·数据结构
Zero不爱吃饭1 小时前
将有序数组转换为二叉搜索树
数据结构·算法
这个世界的真神2 小时前
【每日算法】 洛谷 P12341 【[蓝桥杯 2025 省 A/Python B 第二场] 消消乐】 2025.10.26
python·算法·蓝桥杯
l1t2 小时前
利用DeepSeek改写递归CTE SQL语句为Python程序及优化
数据库·人工智能·python·sql·算法·性能优化·deepseek
杨福瑞3 小时前
数据结构:顺序表讲解(总)
c语言·数据结构
workflower4 小时前
微软PM的来历
java·开发语言·算法·microsoft·django·结对编程