面试经典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;
    }
};
相关推荐
Eloudy2 分钟前
直接法 读书笔记 06 第6章 LU分解
人工智能·算法·ai·hpc
消失的旧时光-19436 分钟前
智能指针(四):体系篇 —— 现代 C++ 内存管理全景图
开发语言·c++
想用offer打牌9 分钟前
一站式了解火焰图的基本使用
后端·面试·架构
仰泳的熊猫17 分钟前
题目1531:蓝桥杯算法提高VIP-数的划分
数据结构·c++·算法·蓝桥杯
汉克老师44 分钟前
GESP2023年12月认证C++二级( 第一部分选择题(1-8))
c++·循环结构·分支结构·gesp二级·gesp2级
刘琦沛在进步1 小时前
如何计算时间复杂度与空间复杂度
数据结构·c++·算法
m0_672703311 小时前
上机练习第30天
数据结构·算法
935961 小时前
机考31 翻译25 单词18
c语言·算法
SuperEugene1 小时前
错误处理与 try/catch:真实项目里应该捕什么错?
前端·javascript·面试
消失的旧时光-19431 小时前
智能指针(三):实现篇 —— shared_ptr 的内部设计与引用计数机制
java·c++·c·shared_ptr