面试经典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;
    }
};
相关推荐
m0_7482402542 分钟前
Windows编程+使用C++编写EXE加壳程序
开发语言·c++·windows
LoveXming2 小时前
Chapter14—中介者模式
c++·microsoft·设计模式·中介者模式·开闭原则
꒰ঌ 安卓开发໒꒱5 小时前
RabbitMQ面试全解析:从核心概念到高可用架构
面试·架构·rabbitmq
前端炒粉5 小时前
18.矩阵置零(原地算法)
javascript·线性代数·算法·矩阵
im_AMBER5 小时前
数据结构 09 二叉树作业
数据结构·笔记·学习
杨筱毅5 小时前
【C++】【常见面试题】最简版带大小和超时限制的LRU缓存实现
c++·面试
暴风鱼划水6 小时前
三维重建【0-D】3D Gaussian Splatting:相机标定原理与步骤
算法·3d
陌路206 小时前
C23构造函数与析构函数
开发语言·c++
_OP_CHEN7 小时前
C++进阶:(二)多态的深度解析
开发语言·c++·多态·抽象类·虚函数·多态的底层原理·多态面试题