mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-31 02:53:42 +00:00
Update 48. 最长不含重复字符的子字符串.md
补充 LeetCode 链接与思路分析,补充滑动窗口遍历配图;更新题目描述并调整代码逻辑以支持全 ASCII 字符。
This commit is contained in:
@@ -1,19 +1,32 @@
|
||||
# 48. 最长不含重复字符的子字符串
|
||||
|
||||
[Leetcode](https://leetcode.cn/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof/)
|
||||
|
||||
## 题目描述
|
||||
|
||||
输入一个字符串(只包含 a\~z 的字符),求其最长不含重复字符的子字符串的长度。例如对于 arabcacfr,最长不含重复字符的子字符串为 acfr,长度为 4。
|
||||
输入一个字符串,求其最长不含重复字符的子字符串的长度。例如对于 arabcacfr,最长不含重复字符的子字符串为 acfr,长度为 4。原书中的字符串只包含 a\~z,力扣的版本还包含数字、符号和空格,因此代码用长度为 128 的数组按 ASCII 码记录。
|
||||
|
||||
## 解题思路
|
||||
|
||||
preIndexs 记录每个字符上一次出现的位置,curLen 是以当前字符结尾、不含重复字符的最长子字符串的长度。遍历到 curI 时,设当前字符上一次出现在 preI:
|
||||
|
||||
- 没有出现过,或者 curI - preI > curLen,说明上一次出现在当前子字符串之外,直接接上当前字符,curLen 加 1;
|
||||
- 否则上一次出现在当前子字符串之内,新的子字符串只能从 preI + 1 开始,curLen 变为 curI - preI。
|
||||
|
||||
以 arabcacfr 为例,遍历到下标 5 的 a 时,上一个 a 在下标 2,仍在当前的 rabc 中,子字符串变为 bca;遍历到最后的 r 时,上一个 r 在下标 1,已经不在当前的 acf 中,curLen 加 1 得到 acfr:
|
||||
|
||||
<div align="center"> <img src="pics/offer48-window-walk.png" width="640px"/> </div><br>
|
||||
|
||||
每个字符只访问一次,时间复杂度 O(N)。
|
||||
|
||||
```java
|
||||
public int longestSubStringWithoutDuplication(String str) {
|
||||
public int dismantlingAction(String str) {
|
||||
int curLen = 0;
|
||||
int maxLen = 0;
|
||||
int[] preIndexs = new int[26];
|
||||
int[] preIndexs = new int[128];
|
||||
Arrays.fill(preIndexs, -1);
|
||||
for (int curI = 0; curI < str.length(); curI++) {
|
||||
int c = str.charAt(curI) - 'a';
|
||||
int c = str.charAt(curI);
|
||||
int preI = preIndexs[c];
|
||||
if (preI == -1 || curI - preI > curLen) {
|
||||
curLen++;
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 176 KiB |
Reference in New Issue
Block a user