CS-Notes/notes/48. 最长不含重复字符的子字符串.md
2019-11-02 17:33:10 +08:00

37 lines
1020 B
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 48. 最长不含重复字符的子字符串
## 题目描述
输入一个字符串只包含 a\~z 的字符求其最长不含重复字符的子字符串的长度例如对于 arabcacfr最长不含重复字符的子字符串为 acfr长度为 4
## 解题思路
```java
public int longestSubStringWithoutDuplication(String str) {
int curLen = 0;
int maxLen = 0;
int[] preIndexs = new int[26];
Arrays.fill(preIndexs, -1);
for (int curI = 0; curI < str.length(); curI++) {
int c = str.charAt(curI) - 'a';
int preI = preIndexs[c];
if (preI == -1 || curI - preI > curLen) {
curLen++;
} else {
maxLen = Math.max(maxLen, curLen);
curLen = curI - preI;
}
preIndexs[c] = curI;
}
maxLen = Math.max(maxLen, curLen);
return maxLen;
}
```
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>