面试经典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;
    }
};
相关推荐
AndrewHZ4 分钟前
【图像处理基石】如何用OpenCV入门计算机视觉?
图像处理·深度学习·opencv·算法·计算机视觉·机器视觉·cv
橘子真甜~1 小时前
C/C++ Linux网络编程9 - TCP服务器实现流程和独立运行
linux·运维·服务器·c++·守护进程·会话组
CQ_YM8 小时前
数据结构之单向链表
c语言·数据结构·链表
暗然而日章9 小时前
C++基础:Stanford CS106L学习笔记 4 容器(关联式容器)
c++·笔记·学习
gihigo19989 小时前
matlab 基于瑞利衰落信道的误码率分析
算法
foxsen_xia9 小时前
go(基础06)——结构体取代类
开发语言·算法·golang
foxsen_xia9 小时前
go(基础08)——多态
算法·golang
leoufung9 小时前
用三色 DFS 拿下 Course Schedule(LeetCode 207)
算法·leetcode·深度优先
巨人张9 小时前
C++火柴人跑酷
开发语言·c++
im_AMBER10 小时前
算法笔记 18 二分查找
数据结构·笔记·学习·算法