-
Notifications
You must be signed in to change notification settings - Fork 25
/
LongestSubstring.java
59 lines (40 loc) · 1.43 KB
/
LongestSubstring.java
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
52
53
54
55
56
57
58
59
package hacktoberfest;
import java.util.*;
public class LongestSubstring {
public static int longestSubstring(String s) {
int len = s.length();
// Base case
if(len == 0) {
return 0;
}
// To keep track of maximum length of the substring
int max = Integer.MIN_VALUE;
HashSet<Character> set = new HashSet<>();
int left = 0;
// Outer loop for traversing the string
for (int right = 0; right < len; right++) {
// If any duplicate element is found
if (set.contains(s.charAt(right))) {
while (left < right && set.contains(s.charAt(right))) {
set.remove(s.charAt(left));
left++;
}
}
set.add(s.charAt(right));
max = Math.max(max, right - left + 1);
}
return max;
}
// Driver code
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
// Input string
System.out.print("Enter a string = ");
String str = sc.next();
// Call the method
int ans = longestSubstring(str);
System.out.println("Length of the longest substring without repeating characters is = " + ans);
// Close the scanner
sc.close();
}
}