前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode题解---003】Longest Substring Without Repeating Characters

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

作者头像
周三不加班
发布2019-09-04 16:23:41
3980
发布2019-09-04 16:23:41
举报
文章被收录于专栏:程序猿杂货铺程序猿杂货铺

题目

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

Example 1:

代码语言:javascript
复制
Input: "abcabcbb"Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

代码语言:javascript
复制
Input: "bbbbb"Output: 1Explanation: The answer is "b", with the length of 1.

Example 3:

代码语言:javascript
复制
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
复制
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
复制
代码语言:javascript
复制
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
复制

03

解法三

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

代码语言:javascript
复制
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
复制

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
复制
 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
复制
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 删除。

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用set
  • 使用字典
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档