面试经典150题——Day31

文章目录

一、题目

3. Longest Substring Without Repeating Characters

Given a string s, find the length of the longest

substring

without repeating characters.

Example 1:

Input: s = "abcabcbb"

Output: 3

Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"

Output: 1

Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"

Output: 3

Explanation: The answer is "wke", with the length of 3.

Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Constraints:

0 <= s.length <= 5 * 104

s consists of English letters, digits, symbols and spaces.

题目来源: leetcode

二、题解

双指针+滑动窗口

cpp 复制代码
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.length();
        if(n == 0) return 0;
        int i = 0;
        unordered_map<char,int> map;
        map[s[i]] = 1;
        int res = 1;
        for(int j = 1;j < n;j++){
            while(map[s[j]] == 1 && i < j){
                map[s[i]] = 0;
                i++;
            }
            if(map[s[j]] != 1) map[s[j]] = 1;
            res = max(res,j - i + 1);
        }
        return res;
    }
};
相关推荐
一个初入编程的小白22 分钟前
数据结构:二叉树链式结构的实现
数据结构
再吃一根胡萝卜3 小时前
08 · 前端:Vue3 + SSE 流式与执行链路可视化
面试
辰烨chenye3 小时前
LeetCode Hot 100 题解 · 普通数组篇
算法·leetcode·职场和发展
再吃一根胡萝卜3 小时前
03 · 后端:FastAPI 与分层架构
面试
hqyjzsb6 小时前
零 AI 项目经验,学 Python 转型 AI 的正确顺序是什么?
开发语言·人工智能·python·算法·职场和发展·数据挖掘·数据分析
辰烨chenye6 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
微功夫信息技术7 小时前
分层多智能体强化学习驱动的非急救转运公平 - 效率统一调度系统研究与实践
人工智能·学习·算法·动态规划
sanjiaomao3337 小时前
从论文公式到Python实现:用单元测试校验滑动平均算法
python·算法·单元测试
Keven_117 小时前
算法札记:ACM适用的很骚的C++语法(持续更新)
开发语言·c++
乐迪信息7 小时前
如何通过AI防爆摄像机精准判断船舶超速?
大数据·人工智能·算法·安全·目标跟踪