One, Title Description
Given a string, you find out which does not contain a repeated character longest substring length.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: Because the longest substring of characters without repetition is "abc", so its length is 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: Because the longest substring is repeated characters without "b", so that its length is 1.
Example 3:
Input: "bbbbb"
Output: 1
Explanation: Because the longest substring is repeated characters without "b", so that its length is 1.
Second, the solution
There are two ideas:
1, Violence method: using a nested loop to match one by one, the time complexity is O (n * n), the spatial complexity is O (n)
2, the sliding window method : when there is a repeat of the time, then it can not use that repeating characters already recorded, and to have it moved to its rear one [image dump outer link fails, the source station may have anti-theft chain mechanism, it is recommended to save the pictures uploaded directly down (img-SldKCMXl-1584791396069) ( C: \ Users \ dell \ AppData \ Roaming \ Typora \ typora-user-images \ image-20200319230634286.png)]
If character c is the emergence of repetition, we put a pointer to the next one, then the substring certain there will be repeated until the first of next c it possible to eliminate duplication.
Remind yourself: sliding window does not have to put a pointer to the specified location, you can look at what move! ! !
2.1 Violence Act
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] char_num; //保存字符出现的次数
int max = 0, temp = 0;
for(int i = 0; i < s.length(); i++) {
temp = 0;
char_num = new int[128]; //ASCLL 的字符集有 128 种
for(int j = i; j < s.length(); j++) {
int index = s.charAt(j);
if(char_num[index] == 0){
char_num[index]++;
temp++;
max = (temp > max) ? temp : max;
} else break;
}
}
return max;
}
}
//官方已经说明暴力解法会超时,但他们是使用 hashset 来求解的,我用数组并没有超时
2.2 sliding window
Ⅰ, using set
class Solution {
public int lengthOfLongestSubstring(String s) {
int max = 0, temp = 0, i = 0, j = 0;
int length = s.length();
Set<Character> set = new HashSet<>(); //滑动窗口的 set 解法
//用窗口来进行优化
while(i < length && j < length) {
//窗口是一个 [start, end],则 j 是 end,i 是start
if(!set.contains(s.charAt(j))) {
set.add(s.charAt(j));
j++;
max = (j - i > max) ? j - i : max;
} else { //移动 start,是一步一步移动的!
set.remove(s.charAt(i));
i++;
}
}
return max;
}
}
Ⅱ, using an array (barrel)
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] char_num = new int[128];
int length = s.length();
int i =0, j = 0, max = 0;
while(i < length && j < length) {
if(char_num[s.charAt(j)] == 0) { //j 指针指向的字符在数组中如果表示为 0
char_num[s.charAt(j)]++;
j++;
max = (j - i > max) ? j - i : max;
} else {
char_num[s.charAt(i)] = 0; //把 i 指针指向的字符在数组中清除掉
i++;
}
}
return max;
}
}