面试经典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;
    }
};
相关推荐
神仙别闹2 分钟前
基于QT(C++)实现(图形界面)连连看
java·c++·qt
好易学·数据结构10 分钟前
可视化图解算法73:跳台阶(爬楼梯)
数据结构·算法·leetcode·动态规划·笔试
NZT-4810 分钟前
C++基础笔记(三)链表list
c++·笔记·链表
Salt_072811 分钟前
DAY32 类的定义和方法
开发语言·python·算法·机器学习
Tisfy15 分钟前
LeetCode 3433.统计用户被提及情况:(大)模拟
linux·算法·leetcode
_Voosk22 分钟前
C指针存储字符串为何不能修改内容
c语言·开发语言·汇编·c++·蓝桥杯·操作系统
一招定胜负25 分钟前
逻辑回归核心原理与实践指南
算法·逻辑回归·线性回归
吃不饱的得可可33 分钟前
【Linux】mmap文件映射的使用
linux·开发语言·c++
长安er35 分钟前
LeetCode 98. 验证二叉搜索树 解题总结
java·数据结构·算法·leetcode·二叉树·力扣