【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;
    }
};
相关推荐
不会就选b7 小时前
算法日常・每日刷题--<贪心>14
算法
mmmmath_310 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z10 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
醇氧11 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
大熊背11 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
钓鱼的肝12 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
参.商.12 小时前
【Day 53】76. 最小覆盖子串
leetcode·golang
HZZD_HZZD12 小时前
CSDN_批发市场水电漏损归因算法LAM的原理与落地
嵌入式硬件·物联网·算法
shirsl14 小时前
算法 Day 5 树 / 二叉树 + DFS
数据结构·python·算法