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

题目

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

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

词汇

without repeating characters 无重复字符

翻译

求最大无重复字符串

代码实现-Java

解法一

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

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

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;
}
解法二

以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这段扔掉),在这个过程中记录最大窗口长度

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;
}

解法三

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

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;
}

代码实现-Python

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

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

解法一 使用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是对应的,要同时维护。

 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

解法二 使用字典

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

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

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

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

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

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

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

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

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

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

CSDN地址:https://blog.csdn.net/ZBylant
微信公众号 在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值