Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8991843

Browse files
committed
fix leetcode 0003 with go
1 parent 027e732 commit 8991843

File tree

4 files changed

+95
-1
lines changed

4 files changed

+95
-1
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# 3. 无重复字符的最长子串
2+
3+
## 链接
4+
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
5+
6+
## 难度
7+
中等
8+
9+
## 描述
10+
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
11+
12+
示例 1:
13+
```text
14+
输入: "abcabcbb"
15+
输出: 3
16+
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
17+
```
18+
19+
示例 2:
20+
```text
21+
输入: "bbbbb"
22+
输出: 1
23+
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
24+
```
25+
26+
示例 3:
27+
```text
28+
输入: "pwwkew"
29+
输出: 3
30+
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
31+
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
32+
```
33+
34+
## 思路
35+
36+
使用一个 map 类型保存字符上次出现的位置,判断是否出现过
37+
字符没出现过,tmplen ++
38+
字符出现了,赋值 ignore = index ,从这个位置重新计算,ignore 之前的字符认为是没出现过的
39+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package _003_Longest_Substring_Without_Repeating_Characters
2+
3+
func lengthOfLongestSubstring(s string) int {
4+
var max, tmpLen, ignore int
5+
m := make(map[uint8]int)
6+
7+
for i, length := 0, len(s); i < length; i++ {
8+
key := s[i]
9+
val, ok := m[key]
10+
if !ok || val < ignore {
11+
tmpLen++
12+
if tmpLen > max {
13+
max = tmpLen
14+
}
15+
} else {
16+
tmpLen = i - val
17+
ignore = val
18+
}
19+
m[key] = i
20+
}
21+
return max
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package _003_Longest_Substring_Without_Repeating_Characters
2+
3+
import (
4+
"github.com/stretchr/testify/assert"
5+
"testing"
6+
)
7+
8+
func TestOne(t *testing.T) {
9+
tests := []struct {
10+
s string
11+
l int
12+
}{
13+
{
14+
s: "bacabcbb",
15+
l: 3,
16+
},
17+
{
18+
s: "bbbbb",
19+
l: 1,
20+
},
21+
{
22+
s: "pwwkew",
23+
l: 3,
24+
},
25+
}
26+
27+
for _, v := range tests {
28+
assert.Equal(t, lengthOfLongestSubstring(v.s), v.l, "should be equal")
29+
}
30+
}

‎LeetCode/Go-Solutions/README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# 使用 Go 刷 LeetCode
22

3-
> 很是别扭,强类型
3+
> 很是别扭,强类型
4+
> 使用 Go 实现,对比 JavaScript 实现,同样的代码快了 5倍+,而且其实我对 Go 不是很熟,有些使用方式并不会优化
45
56
组成
67
- helper,辅助代码
@@ -13,3 +14,5 @@
1314
运行全部测试,进入 ProblemSet 目录,运行 `go test -v ./...`
1415

1516
引用第三方库使用了 go modules
17+
18+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /