【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;
    }
};
相关推荐
维克兜率天6 小时前
4.1.3 策略类型全景图:六大策略,你适合哪个
笔记·python·算法·量化
01_ice6 小时前
c++类和对象(中)
c++·算法
纪念 2296 小时前
数据结构排序(一)
数据结构·算法·排序算法
薛定e的猫咪6 小时前
(NeurIPS 2021)MatNet:面向矩阵型关系数据的神经组合优化编码器
人工智能·深度学习·线性代数·算法·矩阵
高亦真6 小时前
今天是学习嵌入式的第32天
linux·学习·算法
鹿角片ljp15 小时前
LeetCode 236. 二叉树的最近公共祖先|递归后序
算法
luj_176815 小时前
大律师考核应重能力与科技素养
c语言·开发语言·c++·经验分享·算法
无定义_15 小时前
Floyd——Warshall
算法
刃神太酷啦15 小时前
Linux 系统 MySQL 完整安装配置教程:从卸载 MariaDB 到优化 my.cnf----《Hello MySQL!》(1)
android·linux·c语言·c++·mysql·leetcode·mariadb
带多刺的玫瑰16 小时前
Leecode#9刷题之回文数
数据结构·算法