面试经典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;
    }
};
相关推荐
qq_45424503几秒前
SkeletonFlow:基于组合子逻辑与范畴论的数据流处理框架
数据结构·c#
王老师青少年编程6 分钟前
2020年信奥赛C++提高组csp-s初赛真题及答案解析(阅读程序第1题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
pp起床9 分钟前
动态规划 | part03
算法·动态规划
会周易的程序员18 分钟前
cNetgate插件架构设计详解 动态库 脚本二开lua, python, javascript
javascript·c++·python·物联网·lua·iot
mit6.82419 分钟前
合法括号字符串|递归|树
算法
普通网友20 分钟前
C++与Rust交互编程
开发语言·c++·算法
逆境不可逃32 分钟前
【春节篇】LeetCode 热题 100 之 238.除了自身以外数组的乘积
数据结构·算法·leetcode
铸人1 小时前
再论自然数全加和 - 质数螺旋及其生成程序
数学·算法·数论·复数
xyty33201 小时前
QImageReader 的全局静态锁原理
c++·windows·qt
散峰而望1 小时前
【算法竞赛】堆和 priority_queue
开发语言·数据结构·c++·算法·贪心算法·动态规划·推荐算法