Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 4fb5895

Browse files
aQuaaQua
aQua
authored and
aQua
committed
387 finish. 16ms
1 parent 5206349 commit 4fb5895

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# [387. First Unique Character in a String](https://leetcode.com/problems/first-unique-character-in-a-string/)
2+
3+
## 题目
4+
5+
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
6+
7+
Examples:
8+
9+
```text
10+
s = "leetcode"
11+
return 0.
12+
13+
s = "loveleetcode",
14+
return 2.
15+
```
16+
17+
Note: You may assume the string contain only lowercase letters.
18+
19+
## 解题思路
20+
21+
见程序注释
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package Problem0387
2+
3+
func firstUniqChar(s string) int {
4+
rec := make([]int, 26)
5+
for _, b := range s {
6+
rec[b-'a']++
7+
}
8+
9+
for i, b := range s {
10+
if rec[b-'a'] == 1 {
11+
return i
12+
}
13+
}
14+
15+
return -1
16+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package Problem0387
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
// tcs is testcase slice
11+
var tcs = []struct {
12+
s string
13+
ans int
14+
}{
15+
16+
{
17+
"leetcode",
18+
0,
19+
},
20+
21+
{
22+
"loveleetcode",
23+
2,
24+
},
25+
26+
{"aabbcc", -1},
27+
28+
// 可以有多个 testcase
29+
}
30+
31+
func Test_firstUniqChar(t *testing.T) {
32+
ast := assert.New(t)
33+
34+
for _, tc := range tcs {
35+
fmt.Printf("~~%v~~\n", tc)
36+
ast.Equal(tc.ans, firstUniqChar(tc.s), "输入:%v", tc)
37+
}
38+
}
39+
40+
func Benchmark_firstUniqChar(b *testing.B) {
41+
for i := 0; i < b.N; i++ {
42+
for _, tc := range tcs {
43+
firstUniqChar(tc.s)
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)