forked from TARANG0503/DSA-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlengthOfLongestSubstring.java
30 lines (30 loc) · 1023 Bytes
/
lengthOfLongestSubstring.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
import java.util.*;
class LongestSubstring {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter a string: ");
String str = sc.nextLine();
System.out.println(lengthOfLongestSubstring(str));
}
public static int lengthOfLongestSubstring(String s) {
List<String> m = new ArrayList();
int answer = 0;
for (char i : s.toCharArray()) {
if (m.contains(String.valueOf(i))) {
final int ix = m.indexOf(String.valueOf(i));
final List<String> tmp = m.subList(ix+1, m.size());
if (answer < m.size()) {
answer = m.size();
}
tmp.add(String.valueOf(i));
m = tmp;
} else {
m.add(String.valueOf(i));
}
}
if (m.size() > answer) {
answer = m.size();
}
return answer;
}
}