Leetcode - Longest Substring Without Repeating Characters

本文介绍了一种求解字符串中最长无重复字符子串长度的算法,提供了两种实现方法:一种是简单粗暴但效率较低的方法;另一种是通过记录字符最后出现的位置来优化左指针移动,达到线性时间复杂度。

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

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
[分析] 下面给出的两种方法基本思路一致,使用两指针表示滑动窗口的左右边界,窗口中的
字符均不重复。若遇到新字符,右指针往前走,若遇到窗口中已有字符,寻找窗口中该字符的下标idx,左指针移到idx下一个位置。方法1是O(n^2),方法2是O(n)的, 方法2的高效之处在于使用一个table保存了所遇字符上一次的出现位置,因此可以在单位时间内完成更新左指针操作。


// Method 2 : 开一个字符集大小的数组存储遍历s时遇到的字符的最近一次位置,
//相较Method 1, 节省了寻找上次出现位置以及从HashSet删除新窗口外的字符操作开销
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0)
return 0;
int n = s.length();
int max = 0;
int[] lastPosTable = new int[256];
for (int i = 0; i < 256; i++)
lastPosTable[i] = -1;
int i = 0, j = 0;
while (j < n) {
int lastPos = lastPosTable[s.charAt(j)];
if (lastPos >= i) {
max = Math.max(max, j - i);
i = lastPos + 1;
}
lastPosTable[s.charAt(j)] = j;
j++;
}
return Math.max(max, j - i);
}

// Method 1: Brute force, time out
// 2 pointer, characters in the sliding window are distinct
// which store in the hashset
public int lengthOfLongestSubstring1(String s) {
if (s == null || s.length() == 0)
return 0;
HashSet<Character> set = new HashSet<Character>();
int i = 0, j = 0;
int max = 0;
int n = s.length();
while (j < n) {
char curr = s.charAt(j);
if (set.contains(curr)){
max = Math.max(max, set.size());
while (i < j && s.charAt(i) != curr) {
set.remove(s.charAt(i++));
}
set.remove(s.charAt(i++));
}
set.add(curr);
j++;
}
return Math.max(max, set.size());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值