【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;
    }
};
相关推荐
Zachery Pole6 小时前
CCF-CSP备战NO.5链表(1)
数据结构·链表
圣光SG8 小时前
Java操作题练习(七)
java·开发语言·算法
Cx330_FCQ10 小时前
Tmux使用
服务器·git·算法
拳里剑气11 小时前
C++算法:多源BFS
c++·算法·宽度优先·多源bfs
ysa05103011 小时前
【板子】短序列dp(换成维护更小常数维度的dp)
c++·笔记·算法·板子
shwill12312 小时前
PID 算法(三)--- 增量 PID ↔ 单神经元 PID 等价映射
linux·算法
wabs66613 小时前
关于图论【卡码网110.字符串迁移的思考】
数据结构·算法·图论
hanlin0313 小时前
刷题笔记:力扣第242、349题(哈希表)
笔记·算法·leetcode
浮沉98714 小时前
二分查找算法例题(二)
算法
only-qi15 小时前
大模型Agent面试攻略:落地工程痛点、评估体系与Agentic RAG核心精讲
人工智能·算法·面试·职场和发展·langchain·rag