面试经典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;
    }
};
相关推荐
Keep_Trying_Go1 小时前
基于无监督backbone无需训练的类别无关目标统计CountingDINO算法详解
人工智能·python·算法·多模态·目标统计
有时间要学习1 小时前
面试150——第三周
算法·面试
一车小面包1 小时前
Neo4j中的APOC
算法·neo4j
梵尔纳多1 小时前
OpenGL 坐标映射
c++·图形渲染
H_BB1 小时前
前缀和算法详解
数据结构·算法
聆风吟º2 小时前
【数据结构手札】时间复杂度详解:概念 | 大O渐进表示法 | 习题
数据结构·算法·时间复杂度·大o渐进表示法
zs宝来了2 小时前
Spring Boot启动流程源码深度解析:电商订单系统面试实战
java·spring boot·面试·源码分析·电商
有意义2 小时前
从重复计算到无效渲染:用对 useMemo 和 useCallback 提升 React 性能
react.js·面试·前端框架
山楂树の3 小时前
买卖股票的最佳时机(动态规划)
算法·动态规划
大头流矢3 小时前
C++的类与对象·三部曲:初阶
开发语言·c++