【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;
    }
};
相关推荐
圣保罗的大教堂1 小时前
leetcode 1386. 安排电影院座位 中等
leetcode
看我眼色行事^ \/ ^1 小时前
2024.05.11 360春招WEB前端编程题
算法
来一碗刘肉面1 小时前
有向无环图 DAG(描述表达式)
数据结构
一只肥瘫瘫1 小时前
编码器 PLL 角度与速度观测器原理
人工智能·算法
Nil2082 小时前
leetcode 146LRU缓存
算法·leetcode·缓存
郝学胜_神的一滴2 小时前
干货版《算法导论》18:遍历增删原理、时间复杂度与集合序列实现全解
数据结构·算法
-dzk-3 小时前
【滑动窗口】LC 3.无重复字符的最长子串
算法·滑动窗口
BK贝壳3 小时前
Python底层:1亿个布尔值缓存失效标记,list爆内存numpy爆拷贝,bool-hybrid-array混合存储实测
数据结构·python·缓存·性能优化·list·numpy
zzxdear3 小时前
用 OR-Tools CP-SAT 求解最简单的柔性作业车间调度(FJSP)
算法
luj_17683 小时前
变频技术核心原理揭秘
服务器·c语言·开发语言·经验分享·算法