Created
May 7, 2022 06:17
-
-
Save tomer-ben-david/8daafbd8fa75080d8b029daec716923c to your computer and use it in GitHub Desktop.
LeetCode 2 Find longest subsequence in string non repeating
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int lengthOfLongestSubstring(String s) { | |
int l = 0; | |
int result = 0; | |
Set<Character> set = new HashSet<>(); | |
// We start with right pointer from 0, both left and right are at 0!. | |
for (int r = 0; r < s.length(); r++) { | |
// As long as we have duplicates move left first. Trick! at first 0,0 no duplicates! | |
while (set.contains(s.charAt(r))) { | |
set.remove(s.charAt(l)); // Note we remove what left points to! until we remove all duplicates with left. | |
l++; | |
} | |
// Now add current different r into the set. | |
set.add(s.charAt(r)); | |
// Trick! Note that when r = l = 0 then s is also empty and we would put in result 0 - 0 + 1 ! | |
result = Math.max(result, r - l + 1); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment