Skip to content

Instantly share code, notes, and snippets.

@wayetan
Last active September 14, 2018 05:14
Show Gist options
  • Save wayetan/8265857 to your computer and use it in GitHub Desktop.
Save wayetan/8265857 to your computer and use it in GitHub Desktop.
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.
*/
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
int i = 0, j = 0;
int maxLen = 0;
boolean[] exists = new boolean[256];
while(j < n){
if(exists[s.charAt(j)]){
// met the repeat character, update the maxlen;
maxLen = Math.max(maxLen, j - i);
// update pointer i
while(s.charAt(i) != s.charAt(j)){
exists[s.charAt(i)] = false;
i++;
}
i++;
j++;
} else {
exists[s.charAt(j)] = true;
j++;
}
}
maxLen = Math.max(maxLen, n - i);
return maxLen;
}
public int lengthOfLongestSubstring(String s) {
int i = 0, j = 0, max = 0;
Set<Character> set = new HashSet<>();
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;
}
public int lengthOfLongestSubstring(String s) {
boolean[] exist = new boolean[256];
int i = 0, maxLen = 0;
for(int j = 0; j < s.length(); j++) {
while(exist[s.charAt(j)]) {
exist[s.charAt(i)] = false;
i++;
}
exist[s.charAt(j)] = true;
maxLen = Math.max(maxLen, j - i + 1);
}
return maxLen;
}
}
@devdil
Copy link

devdil commented Jul 22, 2018

how does the second solution is work, wouldn't it get stuck in a forever while loop?

@CretaceousConstructor
Copy link

elegent solution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment