Hello World

吞风吻雨葬落日 欺山赶海踏雪径

0%

Longest Substring Without Repeating Characters

题目

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

1
2
3
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

1
2
3
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

1
2
3
4
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

我的解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int length = s.length();

// 记录字符串的最大位置 下标是ascii , 值是位置
int [] arr = new int[128];
Arrays.fill(arr,-1);

// 窗口边界
int left = 0;

int max = 0;
for (int i = 0; i < length; i++) {
int ascii = s.charAt(i);
if(arr[ascii] >= left ){
// 有重复的,左边边界往前推到重复的下一位
left = arr[ascii]+1;
}else{
// 没有就用当前的刷新一下最大长度
max = Math.max(max,i-left + 1);
}
// 记录最大的位置
arr[ascii] = i ;
}
return max;
}
}

链接:https://leetcode.cn/problems/longest-substring-without-repeating-characters