-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC3_LongestSubstringWithoutRepeatingCharacters.java
More file actions
65 lines (57 loc) · 1.58 KB
/
LC3_LongestSubstringWithoutRepeatingCharacters.java
File metadata and controls
65 lines (57 loc) · 1.58 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package practise.leetCode;
import java.util.HashMap;
//sliding window
public class LC3_LongestSubstringWithoutRepeatingCharacters {
public static void main(String[] args) {
String str = "pwwkew";
System.out.println("Length of longest substring: " + lengthOfLongestSubstring(str));
}
public static int lengthOfLongestSubstring(String str) {
Integer i = 0, j = 0, maxLen = 0;
HashMap<Character, Integer> map = new HashMap<>();
for (j = 0; j < str.length(); j++) {
Character currentChar = str.charAt(j);
if (map.containsKey(currentChar))
i = Math.max(i, map.get(currentChar) + 1);
map.put(currentChar, j);
maxLen = Math.max(maxLen, j - i + 1);
}
return maxLen;
//
// if (str.length() == 1)
// return 1;
// else {
// Integer i, j = 0, len = 0, maxLen = 0;
// HashMap<Character, Integer> map = new HashMap<Character, Integer>();
//
// for (i = 0; i < str.length(); i++) {
// j = i;
// while (!map.containsKey(str.charAt(j)) && j < str.length() - 1) {
// len++;
// map.put(str.charAt(j), j);
// j++;
// }
// maxLen = Math.max(maxLen, len);
// len = 0;
// if (!map.isEmpty())
// map.clear();
// }
//
// return maxLen;
// }
//
// using two pointers
// Integer l = 0,r = 0,maxLength = 0;
// Map<Character, Integer> map = new HashMap<>();
// for (r=0;r<str.length();r++) {
// if (map.containsKey(str.charAt(r))) {
// map.put(str.charAt(r), r);
// l=map.get(str.charAt(r));
// } else {
// map.put(str.charAt(r), r);
// maxLength=Math.max(maxLength, r-l+1);
// }
// }
// return maxLength;
}
}