Skip to content

Commit c117dfd

Browse files
committed
Merge pull request #86 from kingeasternsun/patch-1
Update 0387.First-Unique-Character-in-a-String.md
2 parents e3fd0d2 + 2c41ea3 commit c117dfd

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

leetcode/0387.First-Unique-Character-in-a-String/387. First Unique Character in a String.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package leetcode
22

3+
// 解法一
34
func firstUniqChar(s string) int {
45
result := make([]int, 26)
56
for i := 0; i < len(s); i++ {
@@ -12,3 +13,34 @@ func firstUniqChar(s string) int {
1213
}
1314
return -1
1415
}
16+
17+
// 解法二
18+
// 执行用时: 8 ms
19+
// 内存消耗: 5.2 MB
20+
func firstUniqChar1(s string) int {
21+
charMap := make([][2]int, 26)
22+
for i := 0; i < 26; i++ {
23+
charMap[i][0] = -1
24+
charMap[i][1] = -1
25+
}
26+
for i := 0; i < len(s); i++ {
27+
if charMap[s[i]-'a'][0] == -1 {
28+
charMap[s[i]-'a'][0] = i
29+
} else { //已经出现过
30+
charMap[s[i]-'a'][1] = i
31+
}
32+
}
33+
res := len(s)
34+
for i := 0; i < 26; i++ {
35+
//只出现了一次
36+
if charMap[i][0] >= 0 && charMap[i][1] == -1 {
37+
if charMap[i][0] < res {
38+
res = charMap[i][0]
39+
}
40+
}
41+
}
42+
if res == len(s) {
43+
return -1
44+
}
45+
return res
46+
}

website/content/ChapterFour/0387.First-Unique-Character-in-a-String.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ Given a string, find the first non-repeating character in it and return it's ind
2424
## 解题思路
2525

2626
- 简单题,要求输出第一个没有重复的字符。
27+
- 解法二这个思路只超过 81% 的用户,但是如果测试样例中 s 的字符串很长,但是满足条件的字符都在靠后的位置的话,这个思路应该会更有优势。通过记录每个字符的第一次出现的位置和最后一次出现的位置。第一次对 s 进行一次遍历。第二次仅仅对数组进行遍历就可以了。
2728

2829

2930
## 代码
@@ -32,6 +33,7 @@ Given a string, find the first non-repeating character in it and return it's ind
3233

3334
package leetcode
3435

36+
// 解法 一
3537
func firstUniqChar(s string) int {
3638
result := make([]int, 26)
3739
for i := 0; i < len(s); i++ {
@@ -45,4 +47,35 @@ func firstUniqChar(s string) int {
4547
return -1
4648
}
4749

50+
// 解法 二
51+
// 执行用时: 8 ms
52+
// 内存消耗: 5.2 MB
53+
func firstUniqChar1(s string) int {
54+
charMap := make([][2]int, 26)
55+
for i := 0; i < 26; i++ {
56+
charMap[i][0] = -1
57+
charMap[i][1] = -1
58+
}
59+
for i := 0; i < len(s); i++ {
60+
if charMap[s[i]-'a'][0] == -1 {
61+
charMap[s[i]-'a'][0] = i
62+
} else { //已经出现过
63+
charMap[s[i]-'a'][1] = i
64+
}
65+
}
66+
res := len(s)
67+
for i := 0; i < 26; i++ {
68+
//只出现了一次
69+
if charMap[i][0] >= 0 && charMap[i][1] == -1 {
70+
if charMap[i][0] < res {
71+
res = charMap[i][0]
72+
}
73+
}
74+
}
75+
if res == len(s) {
76+
return -1
77+
}
78+
return res
79+
}
80+
4881
```

0 commit comments

Comments
 (0)