面试经典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;
    }
};
相关推荐
YGGP7 小时前
【Golang】LeetCode 42. 接雨水
算法·leetcode·职场和发展
仰泳的熊猫7 小时前
题目1466:蓝桥杯基础练习VIP-字符串对比
数据结构·c++·算法·蓝桥杯
Renhao-Wan7 小时前
Java算法实践(二):堆与PriorityQueue实战
java·数据结构·算法
每天要多喝水7 小时前
动态规划Day29:打家劫舍
算法·动态规划
.小小陈.7 小时前
Python基础语法详解4:函数、列表与元组全解析
开发语言·c++·python·学习
IT猿手7 小时前
多目标鲸鱼优化算法(MOWOA)求解46个多目标函数及一个工程应用,包含四种评价指标,MATLAB代码
开发语言·算法·matlab
罗湖老棍子7 小时前
星际能量矩阵:树形 DP 的递归与非递归双解
算法·动态规划·dfs·bfs·树型dp·树型动态规划
@––––––7 小时前
力扣hot100—系列7-二分查找
数据结构·算法·leetcode
MicroTech20257 小时前
微算法科技(NASDAQ: MLGO)引入量子启发式算法与区块链融合的数据预测与安全传输方案
科技·算法·启发式算法
近津薪荼8 小时前
优选算法——前缀和(5):和为 K 的子数组
算法