3 Longest Substring Without Repeating Characters

博客围绕求无重复字符的最长子串问题展开。给出多个示例,介绍使用滑动窗口解法,在字符串中‘向右滑动’,将新字符纳入集合,用变量记录最长无重复子串长度。若新字符重复则缩短窗口,时间复杂度为O(N)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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.

解法思路

  • 既然是让求没有重复元素的最大子串,于是想到用滑动窗口在给定字符串 s 中“向右滑动”的过程中,将新纳入滑动窗口的字符丢入一个集合;
  • 用一个变量 lengthRecord 记录出现的无重复子串的最长长度;
  • 如果每次纳入滑动窗口的新字符都能成功的丢入这个集合,那么记录 lengthRecord 就会不断被打破;
  • 如果纳入滑动窗口的新字符无法被丢入滑动窗口,说明滑动窗口中已经存在这个字符,那么就要缩短滑动窗口到与新字符重复的字符的右边,此时记录 lengthRecord 不因滑动窗口纳入新的字符而被打破,于是继续“向右滑动”窗口,期待以后的某一时刻,当有新字符纳入滑动窗口时,会打破记录 lengthRecord

时间复杂度

  • O(N);

关键词

滑动窗口 哈希表 双指针 字符串

解法实现

  • 滑动窗口的边界用变量 lr 表示,滑动窗口中的字符用集合 windowSet 盛接;
package leetcode._3;

import java.util.HashSet;
import java.util.Set;

public class Solution {

    public int lengthOfLongestSubstring(String s) {

        int l = 0, r = -1;
        int lengthRecord = 0;
        Set<Character> windowSet = new HashSet<>(s.length());

        while (l < s.length() && r + 1 < s.length()) {
            r++;
            char c = s.charAt(r);
            boolean isAdded = windowSet.add(c);
            if (!isAdded) {
                while (s.charAt(l) != c && l + 1 < s.length()) {
                    windowSet.remove(s.charAt(l));
                    l++;
                }
                windowSet.remove(s.charAt(l));
                l++;
                windowSet.add(c);
            }
            lengthRecord = Math.max(lengthRecord, windowSet.size());
        }

        return lengthRecord;
    }

    public static void main(String[] args) {
        int result = (new Solution()).lengthOfLongestSubstring("abcabcbb");

        System.out.println(result);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值