面试经典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;
    }
};
相关推荐
菜择贰14 小时前
B树的性质和查找、插入、删除操作
数据结构·b树
LDR00614 小时前
接口焦虑终结者:LDR6020 芯片如何重新定义 Type-C 拓展坞与多设备互联时代
数据结构·经验分享·智能音箱
房开民15 小时前
可变参数模板
java·开发语言·算法
t***54415 小时前
如何在现代C++中更有效地应用这些模式
java·开发语言·c++
_深海凉_15 小时前
LeetCode热题100-最小栈
java·数据结构·leetcode
不知名的忻16 小时前
Morris遍历(力扣第99题)
java·算法·leetcode·morris遍历
状元岐16 小时前
C#反射从入门到精通
java·javascript·算法
itman30116 小时前
C语言、C++与C#深度研究:从底层到现代开发演进全解析
c语言·c++·c·内存管理·编译模型
_深海凉_16 小时前
LeetCode热题100-除了自身以外数组的乘积
数据结构·算法·leetcode
Kk.080217 小时前
项目《基于Linux下的mybash命令解释器》(一)
前端·javascript·算法