From 44c94e5a96f6fbc1f3d1ac9e1f9ce90898373d97 Mon Sep 17 00:00:00 2001 From: Jason Staten Date: Fri, 30 Sep 2022 07:27:56 -0600 Subject: [PATCH] norepeat --- norepeat/norepeat.go | 30 +++++++++++++++++++++++++++++ norepeat/norepeat_test.go | 38 +++++++++++++++++++++++++++++++++++++ norepeat/readme.md | 40 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 108 insertions(+) create mode 100644 norepeat/norepeat.go create mode 100644 norepeat/norepeat_test.go create mode 100644 norepeat/readme.md diff --git a/norepeat/norepeat.go b/norepeat/norepeat.go new file mode 100644 index 0000000..759fd55 --- /dev/null +++ b/norepeat/norepeat.go @@ -0,0 +1,30 @@ +package norepeat + +func max(x, y int) int { + if x > y { + return x + } + return y +} + +func lengthOfLongestSubstring(s string) int { + positions := map[byte]int{} + longest := 0 + + for i := 0; i < len(s); i++ { + char := s[i] + pos, exists := positions[char] + positions[char] = i + longest = max(longest, len(positions)) + if exists { + positions = map[byte]int{} + i = pos + } + } + + return longest +} + +func LengthOfLongestSubstring(s string) int { + return lengthOfLongestSubstring(s) +} diff --git a/norepeat/norepeat_test.go b/norepeat/norepeat_test.go new file mode 100644 index 0000000..d31be34 --- /dev/null +++ b/norepeat/norepeat_test.go @@ -0,0 +1,38 @@ +package norepeat_test + +import ( + "testing" + + "git.jxs.me/leetgo/norepeat" + "github.com/stretchr/testify/require" +) + +func TestEmpty(t *testing.T) { + result := norepeat.LengthOfLongestSubstring("") + + require.Equal(t, 0, result) +} + +func TestSingle(t *testing.T) { + result := norepeat.LengthOfLongestSubstring("a") + + require.Equal(t, 1, result) +} + +func TestDouble(t *testing.T) { + result := norepeat.LengthOfLongestSubstring("ab") + + require.Equal(t, 2, result) +} + +func TestRepeat(t *testing.T) { + result := norepeat.LengthOfLongestSubstring("dad") + + require.Equal(t, 2, result) +} + +func TestQuad(t *testing.T) { + result := norepeat.LengthOfLongestSubstring("hellllo") + + require.Equal(t, 3, result) +} diff --git a/norepeat/readme.md b/norepeat/readme.md new file mode 100644 index 0000000..42982e0 --- /dev/null +++ b/norepeat/readme.md @@ -0,0 +1,40 @@ +3. Longest Substring Without Repeating Characters +Medium + +Given a string s, find the length of the longest substring without repeating characters. + + + +Example 1: + +``` +Input: s = "abcabcbb" +Output: 3 +Explanation: The answer is "abc", with the length of 3. +``` + +Example 2: + +``` +Input: s = "bbbbb" +Output: 1 +Explanation: The answer is "b", with the length of 1. +``` + +Example 3: + +``` +Input: s = "pwwkew" +Output: 3 +Explanation: The answer is "wke", with the length of 3. +Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. +``` + + + +Constraints: + + 0 <= s.length <= 5 * 104 + s consists of English letters, digits, symbols and spaces. + +