面试经典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;
    }
};
相关推荐
循环过三天几秒前
3-1 PID算法改进(积分部分)
笔记·stm32·单片机·学习·算法·pid
呆瑜nuage10 分钟前
数据结构——堆
数据结构
Ronin30513 分钟前
【C++】类型转换
开发语言·c++
笑衬人心。14 分钟前
HTTPS详解:原理 + 加解密过程 + 面试问答
java·网络协议·http·面试·https
蓝澈112116 分钟前
弗洛伊德(Floyd)算法-各个顶点之间的最短路径问题
java·数据结构·动态规划
zl_dfq19 分钟前
数据结构 之 【堆】(堆的概念及结构、大根堆的实现、向上调整法、向下调整法)(C语言实现)
数据结构
127_127_12721 分钟前
2025 FJCPC 复建 VP
数据结构·图论·模拟·ad-hoc·分治·转化
闪电麦坤9525 分钟前
数据结构:二维数组(2D Arrays)
数据结构·算法
mrbone1129 分钟前
Git-git worktree的使用
开发语言·c++·git·cmake·worktree·gitab
欧阳有财36 分钟前
[java八股文][Mysql面试篇]日志
java·mysql·面试