3. Longest Substring Without Repeating Characters
Last updated
Last updated
/**
*
*
*/
class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLen = 0, j = 0;
Set<Character> set = new HashSet<>();
for(int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if(set.contains(ch)) {
while(j < i) {
if(s.charAt(j) == ch) {
j++;
break;
} else {
set.remove(s.charAt(j));
j++;
}
}
} else {
set.add(ch);
maxLen = Math.max(maxLen, set.size());
}
}
return maxLen;
}
}/**
* Time complexity : O(n). Index j will iterate n times.
*
*/
class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLen = 0, n = s.length();
int[] index = new int[128];
Arrays.fill(index, -1);
for(int j = 0, i = 0; j < n; j++) {
char ch = s.charAt(j);
i = Math.max(i, index[ch]);
maxLen = Math.max(maxLen, j-i+1);
index[ch] = j+1;
}
return maxLen;
}
}