面试经典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;
    }
};
相关推荐
王老师青少年编程6 小时前
2025年【江苏“信息与未来”编程思维】真题及题解(T2:坐标变换)
c++·题解·真题·坐标变换·编程思维·江苏·信息与未来
CS创新实验室7 小时前
算法、齿轮与硅基大脑:数值计算发展简史
人工智能·算法·数值计算
YHHLAI8 小时前
[特殊字符] 面试中的 Promise —— 从入门到精通
前端·javascript·面试
海石9 小时前
1563分的简单题,可能就简单在能被暴力AC
算法·leetcode
海石9 小时前
1400分的dp汗流浃背之【交替子数组计数】
算法·leetcode
奋发向前wcx9 小时前
P2590 树的统计 题目解析
数据结构·算法·深度优先
2023自学中10 小时前
C++ 内存追踪器
linux·c++
imbackneverdie10 小时前
AI4S不止于分子药物:以MedPeer为代表的科研基建打开产业新增量
大数据·人工智能·算法·aigc·科研·学术·ai 4s
额鹅恶饿呃11 小时前
C语言中的数据结构和变量
c语言·数据结构·算法
运行时记录12 小时前
prompt-optimizer skill
算法