【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;
    }
};
相关推荐
m0_5474866610 分钟前
《智能计算》全套课件PDF(武汉工程大学)
算法·贝叶斯算法·智能计算
Shaoshing35 分钟前
LeetCode100 32.最长有效括号
java·数据结构·leetcode
weixin_3077791340 分钟前
Jupyter SQL 表血缘分析并导出 Excel
开发语言·python·sql·算法·excel
Lazyafei1 小时前
560. 和为 K 的子数组
数据结构·算法
小白的高手之路1 小时前
【LeetCode 热题 100】240. 搜索二维矩阵 II|矩阵、二分查找、Z 字形查找(Python)
python·算法·leetcode·矩阵·力扣
geovindu1 小时前
python:DBSCAN
开发语言·后端·python·算法
劲夫学编程1 小时前
leetcode:最长连续序列
leetcode·最长连续序列
Tim_101 小时前
【LeetCode】 525. 连续数组
算法
小蒋学算法2 小时前
算法-将数据流变为多个不相交区间-TreeMap
算法
Mortalbreeze2 小时前
图论算法篇:A*、Floyd、Bellman-Ford、SPFA
数据结构·c++·算法