面试经典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;
    }
};
相关推荐
信奥胡老师4 分钟前
B3930 [GESP202312 五级] 烹饪问题
开发语言·数据结构·c++·学习·算法
许长安8 分钟前
Redis 跳表实现详解
数据库·c++·经验分享·redis·笔记·缓存
paeamecium18 分钟前
【PAT甲级真题】- Shortest Distance (20)
数据结构·c++·算法·pat考试·pat
aisifang0022 分钟前
GPT-Image2去偏见技术新突破
人工智能·算法·机器学习
吴可可12325 分钟前
点在线上判定与多段线分割
算法·c#
折哥的程序人生 · 物流技术专研27 分钟前
《Java 100 天进阶之路》第23篇:缓冲区数据结构 ByteBuffer
java·开发语言·数据结构·后端·面试·求职招聘
REDcker32 分钟前
C++循环与编译器优化详解 别名不变量向量化与GCC Clang验证及perf实践
java·jvm·c++·c·clang·gcc
不剪发的Tony老师32 分钟前
Code::Blocks:一款免费开源的C/C++/Fortran集成开发环境
c语言·c++·ide
咩咦38 分钟前
C++学习笔记10:auto关键字
c++·学习笔记·c++11·auto·类型推导
吴可可1231 小时前
圆弧多段线离散化采样密度优化
算法·c#