parent
18cd04bab4
commit
44c94e5a96
@ -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)
|
||||
}
|
@ -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)
|
||||
}
|
@ -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.
|
||||
|
||||
|
Loading…
Reference in new issue