From 7ed475c60d97fce8041ad8c958749b132a8a76af Mon Sep 17 00:00:00 2001 From: Xevion Date: Wed, 13 Jan 2021 19:28:17 -0600 Subject: [PATCH] longest-substring-without-repeating-characters solution java --- .../Solution.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 longest-substring-without-repeating-characters/Solution.java diff --git a/longest-substring-without-repeating-characters/Solution.java b/longest-substring-without-repeating-characters/Solution.java new file mode 100644 index 0000000..52cd5f4 --- /dev/null +++ b/longest-substring-without-repeating-characters/Solution.java @@ -0,0 +1,26 @@ +// Accepted +// Runtime: 4 ms +// Memory Usage: 39.1 MB +// Submitted: January 13th, 2021 + +class Solution { + public int lengthOfLongestSubstring(String s) { + int max = 0; + // Map stores the character's (latest_index + 1) + Map map = new HashMap(); + + int i = 0; + for (int j = 0; j < s.length(); j++) { + char c = s.charAt(j); + + // If we've already seen this character, move up i (if needed) + if (map.containsKey(c)) + i = Math.max(map.get(c), i); + + max = Math.max(max, j - i + 1); + map.put(c, j + 1); + } + + return max; + } +} \ No newline at end of file