image

Photo Credit: Pixiv - 七淵

LeetCode Solution - Longest Substring Without Repeating Characters

https://leetcode.com/problems/longest-substring-without-repeating-characters/

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.

Solution 1: Using HashSet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0){
return 0;
}
Set<Character> set = new HashSet<Character>();
int max = 0, i = 0, j = 0;
while(j < s.length()){
if(!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
max = Math.max(max, set.size());
} else {
set.remove(s.charAt(i++));
}
}
return max;
}
}

Solution 2: Using ASCII Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0){
return 0;
}
boolean[] isUsed = new boolean[256];
int max = 0, i = 0, j = 0;
while(j < s.length()){
if(!isUsed[s.charAt(j)]){
max = Math.max(max, j - i + 1);
isUsed[s.charAt(j++)] = true;
} else {
isUsed[s.charAt(i++)] = false;
}
}
return max;
}
}

Follow Up: If you want to return the longest substring not the length of it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
public String lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0){
return null;
}
Set<Character> set = new HashSet<Character>();
int max = 0, i = 0, j = 0, pos = 0;
while(j < s.length()){
if(!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
if (max < set.size()) {
max = set.size();
pos = j - 1;
}
}
else{
set.remove(s.charAt(i++));
}
}
return s.substring(pos + 1 - max, pos + 1);
}
}