面试经典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;
    }
};
相关推荐
一直都在5721 分钟前
数据结构入门:二叉排序树的删除算法
数据结构·算法
白云千载尽3 分钟前
ego_planner算法的仿真环境(主要是ros)-算法的解耦实现.
算法·无人机·规划算法·后端优化·ego·ego_planner
hweiyu004 分钟前
排序算法简介及分类
数据结构
tang&9 分钟前
哈希碰撞攻防战:C++闭散列与开散列实现全解析
c++·哈希算法
眠りたいです15 分钟前
现代C++:C++11并发支持库
开发语言·c++·多线程·c++11·c++并发支持库
小灰灰搞电子21 分钟前
Rust可以取代C++么?
开发语言·c++·rust
Swizard25 分钟前
别再只会算直线距离了!用“马氏距离”揪出那个伪装的数据“卧底”
python·算法·ai
T___T27 分钟前
一个定时器,理清 JavaScript 里的 this
前端·javascript·面试
flashlight_hi1 小时前
LeetCode 分类刷题:199. 二叉树的右视图
javascript·算法·leetcode
LYFlied1 小时前
【每日算法】LeetCode 46. 全排列
前端·算法·leetcode·面试·职场和发展