LeetCode - 无重复字符的最长子串

本文介绍了解决LeetCode上“最长不含重复字符的子字符串”问题的一种方法。通过使用HashSet来记录已遍历过的字符,并利用startIndex和endIndex追踪当前无重复子串的位置,实现了高效求解。

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

Github: https://github.com/biezhihua/LeetCode/tree/master/src/com/bzh/leetcode

题目描述:
https://leetcodechina.com/problems/longest-substring-without-repeating-characters/description/

解题思路:
从题目中可以知晓:

  1. 需要能快速判断出是否遍历过相同的字符。
  2. 需要使用startIndexendIndex来表示当前的“无从重复子串“,for循环不适用于当前情况。
  3. 若当前字符是第一次遍历,则将其添加到集合中,并更新endIndex值。
  4. 若当前字符不是第一次遍历,需要更新maxLength,并移除startIndex对应的数据,然后再更新startIndex值。

最终代码:

/**
 * https://leetcodechina.com/problems/longest-substring-without-repeating-characters/description/
 */
public class Code_3_4_LengthOfLongestSubstring {
    @Test
    public void test() {
        Assert.assertEquals(3, lengthOfLongestSubstring("abcabcbb"));
        Assert.assertEquals(1, lengthOfLongestSubstring("bbbbbb"));
        Assert.assertEquals(3, lengthOfLongestSubstring("pwwkew"));
        Assert.assertEquals(1, lengthOfLongestSubstring("p"));
        Assert.assertEquals(0, lengthOfLongestSubstring(""));
        Assert.assertEquals(9, lengthOfLongestSubstring("biezhqwua"));
        Assert.assertEquals(2, lengthOfLongestSubstring("aab"));
        Assert.assertEquals(3, lengthOfLongestSubstring("dvdf"));
        Assert.assertEquals(5, lengthOfLongestSubstring("dveadf"));
    }

    public int lengthOfLongestSubstring(String s) {

        int maxLength = 0;

        if (s == null || s.length() == 0) {
            return maxLength;
        }

        int startIndex = 0;
        int endIndex = 0;

        int length = s.length();
        Set<Character> set = new HashSet<>();
        while (startIndex < length && endIndex < length && startIndex <= endIndex) {
            char c = s.charAt(endIndex);
            if (!set.contains(c)) {
                set.add(c);
                endIndex++;
            } else {
                if (endIndex - startIndex > maxLength) {
                    maxLength = endIndex - startIndex;
                }
                set.remove(s.charAt(startIndex));
                startIndex++;
            }
        }
        if (endIndex - startIndex > maxLength) {
            maxLength = endIndex - startIndex;
        }
        return maxLength;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值