【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;
    }
};
相关推荐
nice_lcj5201 分钟前
排序(4)-归并排序专题——归并排序的分治美学
java·数据结构·算法·排序算法
洛水水16 分钟前
【力扣100题】83.最小栈
算法·leetcode·职场和发展
无忧.芙桃17 分钟前
数据结构之栈
c语言·开发语言·数据结构
nice_lcj52025 分钟前
排序(3)-第三篇:交换排序专题——从冒泡排序到快速排序的效率飞跃
java·数据结构·算法·排序算法
ywl47081208730 分钟前
数据结构之链表反转算法
数据结构·算法·链表
牧子川31 分钟前
019-JSON-Schema-自动生成
算法·大模型·格式化输出·tools
lhjcsubupt41 分钟前
第二十二篇 从随机过程到IMU噪声模型
算法·机器学习·概率论
神仙别闹1 小时前
基于C语言处理机调度算法的实现
服务器·c语言·算法
Brilliantwxx1 小时前
【算法从零到千】【16-23】 二分算法
数据结构·算法
8Qi87 小时前
回文子串(Palindromic Substrings)—— 题解
算法·leetcode·职场和发展·动态规划