面试经典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;
    }
};
相关推荐
王老师青少年编程20 小时前
2020年信奥赛C++提高组csp-s初赛真题及答案解析(阅读程序第2题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
lintax21 小时前
计算pi值-积分法
python·算法·计算π·积分法
你的冰西瓜21 小时前
C++ STL算法——排序和相关操作
开发语言·c++·算法·stl
今儿敲了吗1 天前
29| 高考志愿
c++·笔记·学习·算法
识君啊1 天前
Java 二叉树从入门到精通-遍历与递归详解
java·算法·leetcode·二叉树·深度优先·广度优先
浅念-1 天前
C++ 模板进阶
开发语言·数据结构·c++·经验分享·笔记·学习·模版
紫陌涵光1 天前
77. 组合
c++·算法·leetcode·深度优先
小汉堡编程1 天前
LeekCode第3767题选择K个任务的最大总分:详细思考过程幽默解析 专门为小白准备
算法·leetcode·贪心算法·编程·小白专用教程
小白菜又菜1 天前
Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
python·算法·leetcode