From ecbcea486bec4ef5331641868a4a6b1f94084a39 Mon Sep 17 00:00:00 2001 From: Ly Na Nguyen <39471975+Lynanguyen0515@users.noreply.github.com> Date: Fri, 12 May 2023 23:44:02 -0400 Subject: [PATCH] Create 0003_longest_substring_without_repeating_character --- ...gest_substring_without_repeating_character | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 python_solutions/0003_longest_substring_without_repeating_character diff --git a/python_solutions/0003_longest_substring_without_repeating_character b/python_solutions/0003_longest_substring_without_repeating_character new file mode 100644 index 0000000..b644739 --- /dev/null +++ b/python_solutions/0003_longest_substring_without_repeating_character @@ -0,0 +1,24 @@ +//using sliding window + +import java.util.HashSet; +import java.util.Set; + +class Solution { + public int lengthOfLongestSubstring(String s) { + // HashSet to store the current window of unique characters + Set set = new HashSet<>(); + int n = s.length(); + int ans = 0, i = 0, j = 0; + while (i < n && j < n) { + // try to extend the range [i, j] + if (!set.contains(s.charAt(j))){ + set.add(s.charAt(j++)); + ans = Math.max(ans, j - i); + } + else { + set.remove(s.charAt(i++)); + } + } + return ans; + } +}