3. Longest Substring Without Repeating Characters (M)

Longest Substring Without Repeating Characters (M)

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.

题意

给定一个字符串,找到一个子串,使得子串内没有重复的字符,求该子串的最大长度。

思路

普通解法直接暴力三重循环, O ( N 3 ) O(N^3) O(N3)

较优解法是使用一个“可伸缩”的数组框在字符串上滑动,先向右移动右端点,判断右端点的字符在不在被“伸缩数组”框住的子串中,如果重复则不断向右移动左端点,直到将重复的字符排除在“伸缩数组”外。这样相当于字符串中的每一个字符都要走一遍,复杂度为 O ( 2 N ) = O ( N ) O(2N) = O(N) O(2N)=O(N)

对上述方法的一个优化是,用一个数组记录字符串中每一个字符对应的索引位置,这样在右端点字符重复时,左端点可以直接跳到子串中字符重复的地方,不需要一步一步向右移动左端点。这样只需要右端点走一遍字符串即可,复杂度直接为 O ( N ) O(N) O(N)


代码实现

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int left = 0;
        // right指向子串的右边一个字符
        int right = 0;
        int maxLen = 0;
        Set<Character> set = new HashSet<>();
        while (right < s.length()) {
            if (set.contains(s.charAt(right))) {
                set.remove(s.charAt(left++));
            } else {
                set.add(s.charAt(right++));
                maxLen = Math.max(right - left, maxLen);
            }
        }
        return maxLen;
    }
}

代码实现 - 优化

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int left = 0;
        // right指向子串的最后一个字符
        int right = 0;
        int maxLen = 0;
        // 下标记录字符,值记录该字符在字符串中对应的索引+1
        // 实际上记录的是左端点应该跳转到的位置
        int[] hash = new int[128];
        while (right < s.length()) {
            left = Math.max(left, hash[s.charAt(right)]);
            maxLen = Math.max(maxLen, right - left + 1);
            hash[s.charAt(right)] = ++right;
        }
        return maxLen;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值