面试经典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;
    }
};
相关推荐
有意义9 小时前
深度拆解分割等和子集:一维DP数组与倒序遍历的本质
前端·算法·面试
xlp666hub10 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
用户7268761033710 小时前
解放双手的健身助手:基于 Rokid AR 眼镜的运动计时应用
算法
Wect11 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·typescript
我叫黑大帅11 小时前
Go 语言中处理「未知类型数据」的两大核心手段
后端·面试·go
不想写代码的星星11 小时前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
拉不动的猪12 小时前
重温Vue异步更新队列
前端·javascript·面试
xlp666hub1 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
韭菜炒大葱1 天前
前端经典面试题:从 URL 输入到页面展示,中间经历了什么?
前端·http·面试
kevinzeng1 天前
反射的初步理解
后端·面试