Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【LeetCode题解---003】Longest Substring Without Repeating Characters

【LeetCode题解---003】Longest Substring Without Repeating Characters

作者头像
周三不加班
发布于 2019-09-04 08:23:41
发布于 2019-09-04 08:23:41
43000
代码可运行
举报
文章被收录于专栏:程序猿杂货铺程序猿杂货铺
运行总次数:0
代码可运行

题目

Given a string, find the length of the longest substring without repeating characters.

Example 1:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: "abcabcbb"Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: "bbbbb"Output: 1Explanation: The answer is "b", with the length of 1.

Example 3:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: "pwwkew"Output: 3Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

2

词汇学习

without repeating characters 无重复字符

3

惊人而又蹩脚的中文翻译

求最大无重复字符串

4

代码实现-Java

01

解法一

(代码格式展示不佳的请点击阅读原文)

直接三层for循环 去除不满足条件的情况(当然 这种解法时间复杂度达到了O(n^3)),是不可能通过的

虽然也使用了Hash表,但是没什么很大的效果

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public static boolean unique(String string, int start, int end) {

    Set<Character> set = new HashSet<>();
    char[] array = string.toCharArray();
    for (int i = start; i < end; i++) {
        if (set.contains(array[i])) {
            return false;
        }
        set.add(array[i]);
    }
    return true;
}

/**
 * 就是三个for循环 求解,去掉非法的判断 复杂度达到了 O(n^3)
 * @param s
 * @return
 */
public static int lengthOfLongestSubstring2(String s) {
    int length = s.length();
    int result = 0;
    for (int i = 0; i < length; i++) {
        for (int j = i + 1; j <= length; j++) {
            if (unique(s, i, j)) {
                result = Math.max(result, j - i);
            }
        }
    }
    return result;
}

02

解法2

以abcbef这个串为例

  • 1.用一个Map记录每个元素曾出现的下标,初始为-1
  • 2.说明a还未出现过,令Map<a,-1> 的 value 值变为0,变成Map<a,0>,视为将a"加入当前串",同时长度++
  • 3.同理令Map<a,1> Map<c,2> [2]到[3]时,map.get('b') != -1,说明'b'在前面已经出现过了,
  • 4.此时可得到一个不重复串"abc",刷新当前的最大长度,
  • 5.然后做如下处理:pos[s[0~2]] = -1,
  • 6.亦即将"ab""移出当前串",同时当前长度减去3

滑动窗口 比方说 abcabccc 当你右边扫描到abca的时候你得把第一个a删掉得到bca, 然后"窗口"继续向右滑动,每当加到一个新char的时候,左边检查有无重复的char, 然后如果没有重复的就正常添加,有重复的话就左边扔掉一部分(从最左到重复char这段扔掉),在这个过程中记录最大窗口长度

代码语言:javascript
代码运行次数:0
运行
复制
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public static int lengthOfLongestSubstring3(String s) {
    Map<Character, Integer> map = new HashMap<>(s.length());
    char[] array = s.toCharArray();
    int i, max = 0, pre = -1;
    // 初始化开始的下标
    for (i = 0; i < array.length; i++) {
        map.put(array[i], -1);
    }
    for (i = 0; i < array.length; i++) {
        //更新map中各个字符的下标
        pre = Math.max(pre, map.put(array[i], i));
        //保存暂时的最大无重复子串长度
        max = Math.max(max, i - pre);
        //计算差值后继续更新
        map.put(array[i], i);
    }
    return max;
}
代码语言:javascript
代码运行次数:0
运行
复制

03

解法三

方法和解法二类似,只不过是不同实现方式

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public static int lengthOfLongestSubstring(String s) {
    if (s == null) {
        return 0;
    }
    if (s.length() == 0) {
        return 0;
    }
    Map<Character, Integer> map = new HashMap<>(s.length());
    int max = 0;
    // 转换成字符数组
    char[] array = s.toCharArray();
    for (int i = 0, j = 0; i < array.length; ++i) {
        // map 中已经有这个字符
        if (map.containsKey(array[i])) {
            j = Math.max(j, map.get(array[i]) + 1);
        }
        // 给每个字符一个下标
        /*
            如           p w w k e w
            则对应下标是  0 1 2 3 4 5
         */
        map.put(array[i], i);
        max = Math.max(max, i - j + 1);
    }
    return max;
}
代码语言:javascript
代码运行次数:0
运行
复制

5

代码实现-Python

python实现方式参考了这篇文章

全文地址请点击:https://blog.csdn.net/fuxuemingzhu/article/details/82022530?utm_source=copy

01

解法一

使用set

这个思路比较简单易懂,使用双指针,[left, right]来保存子串的左右区间,对应着这个区间我们维护一个set,这个set里面全部是不重复的字符。

使用while循环,如果right字符不在set中,就让它进去;如果right在,就把left对应的字符给remove出去。

所以,当我们得到一个right位置的字符时,通过移动left和修改[left,right]区间内对应的的set,来保持了一个最小的不重复字符区间。

比如:

a b c b b c b b 0 1 2 3 4 5 6 7

当right移动到3的时候字符时b,此时,set = {a, b, c}中,left=0,字符b在set中。

所以在while循环中反复移动left,当left移动到3的位置时,此时set = {c},字符b已经不在set中。

按照这个方式移动,set的个数最多的值即为最长子串。一定注意:[left, right]区间和set是对应的,要同时维护。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
left, right = 0, 0
chars = set()
res = 0
while left < len(s) and right < len(s):
if s[right] in chars:
if s[left] in chars:
chars.remove(s[left])
left += 1
else:
chars.add(s[right])
right += 1
res = max(res, len(chars))

return res

01

解法二

使用字典

使用字典保存每个字符第一次出现的位置。

当right向后遍历的过程中,如果这个字符在字典中,说明这个字符在前面出现过,即这个区间已经不是题目要求的不含重复字符的区间了,因此,需要移动left。

移动left到哪里呢?有个快速的方法,那就是移动到right字符在字典中出现的位置的下一个位置。

无论如何都会使用right更新字典,另外记录最大区间长度即为所求。

注意,left更新的时候需要保留最大(最右)的位置。举例说明:

对于abba,当right指向最后的a的时候,left指向的是字典中保留的有第一个位置的a,如果不对此进行判断的话,left会移动到第一个字符b。

left一定是向右移动的,不可能撤回到已经移动过的位置。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        left, right = 0, 0
        res = 0
        chars = dict()
        for right in range(len(s)):
            if s[right] in chars:
                left = max(left, chars[s[right]] + 1)
            chars[s[right]] = right
            res = max(res, right - left + 1)
        return res

李达康1分钟前

一个人总要走陌生的路,看陌生的风景,听陌生的歌。总有一天,在某个不经意的瞬间,你会发现,曾经努力想要忘记的事情早已消逝。

以上代码会同步更新在本人的Github和CSDN上

Github地址:https://github.com/Bylant/LeetCode

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-09-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员啊粥 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
LeetCode 3. Longest Substring Without Repeating Characters题目分析
样例 例如,在"abcabcbb"中,其无重复字符的最长子字符串是"abc",其长度为 3。
desperate633
2018/08/22
3360
LeetCode Problem 3: Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
剑影啸清寒
2019/05/26
3620
Sliding Window - 3. Longest Substring Without Repeating Characters
3. Longest Substring Without Repeating Characters
ppxai
2020/09/23
3030
Leetcode3——Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Tyan
2019/05/25
3250
LeetCode——Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.
全栈程序员站长
2022/01/04
1690
LeetCode——Longest Substring Without Repeating Characters
题目: Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the lengt
felixzhao
2018/03/16
6440
Leetcode 题目解析之 Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
ruochen
2022/02/13
1.2K0
3. Longest Substring Without Repeating Characters(无重复字符的最长子串)
Given a string, find the length of the longest substring without repeating characters.
砖业洋__
2023/05/06
1350
3. Longest Substring Without Repeating Characters(无重复字符的最长子串)
LeetCode - Longest Substring Without Repeating Characters
最近启动了刷 LeetCode 的进程,Accepted 了几道题,但两天不到就忘了,即使是留了注释,想想写写笔记还是蛮有必要的,但我不希望不经思考整理就贴一堆代码,把博客搞的乱糟糟的,像 XSDN、XX园、X书 一样,所以也只是想把一些印象深刻的部分,留个笔记。
zgq354
2019/11/24
4620
LeetCode Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
2018/09/04
3560
Leetcode 题目解析之 Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
ruochen
2022/01/14
1.3K0
003. 无重复字符的最长子串 | Leetcode题解
题目要求连续, 我们考虑使用滑动窗口。而这道题就是窗口大小不固定的滑动窗口题目,然后让我们求满足条件的窗口大小的最大值,这是一种非常常见的滑动窗口题目。
苏南
2020/12/16
5480
003. 无重复字符的最长子串 | Leetcode题解
LeetCode 3: 无重复字符的最长子串
Given a string, find the length of the longest substring without repeating characters.
爱写bug
2019/12/02
5080
leetcode刷题(3)——无重复字符的最长子串
输入: “abcabcbb” 输出: 3 解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。 示例 2:
老马的编程之旅
2022/06/22
2000
No.003 Longest Substring Without Repeating Characters
Longest Substring Without Repeating Characters Total Accepted: 167158 Total Submissions: 735821 Difficulty: Medium Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which
mukekeheart
2018/02/27
6380
LeetCode 1-5题 详解 Java版 (三万字 图文详解 LeetCode 算法题1-5 =====>>> <建议收藏>)
给定一个数组和一个目标和,从数组中找两个数字相加等于目标和,输出这两个数字的下标。
猫头虎
2024/04/07
2340
LeetCode 1-5题 详解 Java版 (三万字 图文详解 LeetCode 算法题1-5 =====>>> <建议收藏>)
LeetCode-3-无重复字符的最长字串
首先挨个比较i个字符和i+1结合哈希的方法是失败的,这样求的不适用于dvdf这样的测试用例
benym
2022/07/14
1920
【图解】三种解法不断优化带你手撕 LeetCode第三号题:无重复字符的最长子串
索引从字符串的第一位开始,将后面的字符依次加入到 set 里面。如果 set 里面已经有了该字符,此次循环结束,内循环结束后记录 size。字符串的每一位都用这种方法去计算,得到的最大的 size 即是答案。
帅地
2019/12/19
7840
【图解】三种解法不断优化带你手撕 LeetCode第三号题:无重复字符的最长子串
力扣3-无重复字符的最长子串
暴力求解 复杂度分析 时间复杂度O(n^2) 空间复杂度O(m) class Solution { public int lengthOfLongestSubstring(String s) { int res = 0; for(int i = 0; i < s.length(); i++) { Set<Character> set = new HashSet<>(); for(int j = i; j
后端码匠
2021/08/18
2460
LeetCode: 3_Longest Substring Without Repeating Characters | 求没有重复字符的最长子串的长度 | Medium
题目: Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the lengt
Linux云计算网络
2018/01/11
4610
推荐阅读
相关推荐
LeetCode 3. Longest Substring Without Repeating Characters题目分析
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验