-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestSubstringWithoutRepeatingCharacters.java
More file actions
51 lines (47 loc) · 1.36 KB
/
LongestSubstringWithoutRepeatingCharacters.java
File metadata and controls
51 lines (47 loc) · 1.36 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.Arrays;
/*
* https://leetcode.com/problems/longest-substring-without-repeating-characters/
*/
public class LongestSubstringWithoutRepeatingCharacters {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) {
return 0;
}
int max = 1;
int current = 1;
int size = s.length();
char[] arr = new char[size];
arr[0] = s.charAt(0);
for (int i = 1; i < size; i++) {
char ch = s.charAt(i);
arr[current] = ch;
int index = index(arr, ch, current);
if (index != -1) {
if (max < current) {
max = current;
}
current -= index;
arr = Arrays.copyOfRange(arr, index + 1, arr.length);
continue;
}
current++;
}
if (max < current) {
max = current;
}
return max;
}
private int index(char[] diff, char num, int maxIndex) {
for (int i = 0; i < maxIndex; i++) {
if (diff[i] == num) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(new LongestSubstringWithoutRepeatingCharacters().lengthOfLongestSubstring(
"abcabcbb"
)); // 3
}
}