File tree Expand file tree Collapse file tree 1 file changed +54
-1
lines changed
website/content/ChapterFour Expand file tree Collapse file tree 1 file changed +54
-1
lines changed Original file line number Diff line number Diff line change @@ -45,4 +45,57 @@ func firstUniqChar(s string) int {
45
45
return -1
46
46
}
47
47
48
- ```
48
+ ```
49
+
50
+ ## 思路2
51
+ 这个思路只超过81%的用户,但是如果测试样例中s的字符串很长,但是满足条件的字符都在靠后的位置的话,这个思路应该会更有优势
52
+ - 通过记录每个字符的第一次出现的位置和最后一次出现的位置
53
+ - 第一次对s进行一次遍历
54
+ - 第二次仅仅对数组进行遍历就可以了
55
+
56
+ ## 代码
57
+
58
+ 执行用时: 8 ms
59
+ 内存消耗: 5.2 MB
60
+
61
+
62
+ ``` go
63
+
64
+
65
+ func firstUniqChar (s string ) int {
66
+
67
+ charMap := make ([][2 ]int , 26 )
68
+ for i := 0 ; i < 26 ; i++ {
69
+ charMap[i][0 ] = -1
70
+ charMap[i][1 ] = -1
71
+ }
72
+
73
+ for i := 0 ; i < len (s); i++ {
74
+ if charMap[s[i]-' a' ][0 ] == -1 {
75
+ charMap[s[i]-' a' ][0 ] = i
76
+ } else { // 已经出现过
77
+ charMap[s[i]-' a' ][1 ] = i
78
+ }
79
+
80
+ }
81
+
82
+ res := len (s)
83
+
84
+ for i := 0 ; i < 26 ; i++ {
85
+
86
+ // 只出现了一次
87
+ if charMap[i][0 ] >= 0 && charMap[i][1 ] == -1 {
88
+ if charMap[i][0 ] < res {
89
+ res = charMap[i][0 ]
90
+ }
91
+ }
92
+
93
+ }
94
+
95
+ if res == len (s) {
96
+ return -1
97
+ }
98
+ return res
99
+ }
100
+
101
+ ```
You can’t perform that action at this time.
0 commit comments