Skip to content

Instantly share code, notes, and snippets.

@swarajd
Created September 30, 2019 03:45
Show Gist options
  • Save swarajd/4b3db7307b08ed66f4f0a263fb361775 to your computer and use it in GitHub Desktop.
Save swarajd/4b3db7307b08ed66f4f0a263fb361775 to your computer and use it in GitHub Desktop.
class Solution {
public int lengthOfLongestSubstring(String s) {
HashSet<Character> seenSoFar = new HashSet<Character>();
int curLength = 0;
int longestSoFar = 0;
int start = 0;
int end = 0;
for (int i = 0; i < s.length(); i++) {
char curChar = s.charAt(i);
if (seenSoFar.contains(curChar)) {
longestSoFar = longestSoFar >= curLength ? longestSoFar : curLength;
if (s.charAt(start) == curChar) {
while (start != i && start < i && s.charAt(start) == curChar) {
start++;
curLength--;
}
curLength++;
} else {
while (s.charAt(start) != curChar) {
seenSoFar.remove(s.charAt(start));
start++;
curLength--;
}
start++;
}
} else {
seenSoFar.add(curChar);
curLength++;
end++;
}
}
longestSoFar = longestSoFar >= curLength ? longestSoFar : curLength;
return longestSoFar;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment