【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;
    }
};
相关推荐
业精于勤的牙19 分钟前
浅谈:算法中的斐波那契数(二)
算法·职场和发展
不穿格子的程序员43 分钟前
从零开始写算法——链表篇4:删除链表的倒数第 N 个结点 + 两两交换链表中的节点
数据结构·算法·链表
liuyao_xianhui1 小时前
寻找峰值--优选算法(二分查找法)
算法
dragoooon341 小时前
[hot100 NO.19~24]
数据结构·算法
电子硬件笔记2 小时前
Python语言编程导论第七章 数据结构
开发语言·数据结构·python
Tony_yitao2 小时前
15.华为OD机考 - 执行任务赚积分
数据结构·算法·华为od·algorithm
C雨后彩虹3 小时前
任务总执行时长
java·数据结构·算法·华为·面试
风筝在晴天搁浅3 小时前
代码随想录 463.岛屿的周长
算法
柒.梧.3 小时前
数据结构:二叉排序树构建与遍历的解析与代码实现
java·开发语言·数据结构