6
6
7
7
** 示例:**
8
8
9
- ````
9
+ ```
10
10
s = "abaccdeff"
11
11
返回 "b"
12
12
13
13
s = ""
14
14
返回 " "
15
- ```
15
+ ```
16
16
17
17
** 限制:**
18
18
19
19
- ` 0 <= s 的长度 <= 50000 `
20
20
21
21
## 解法
22
- 有序字典解决。
22
+
23
+ 对字符串进行两次遍历:
24
+
25
+ 第一遍,先用 hash 表(或数组)统计字符串中每个字符出现的次数。
26
+
27
+ 第二遍,只要遍历到一个只出现一次的字符,那么就返回该字符,否则在遍历结束后返回空格。
23
28
24
29
<!-- tabs:start -->
25
30
26
31
### ** Python3**
32
+
27
33
``` python
28
34
import collections
29
35
30
36
class Solution :
31
37
def firstUniqChar (self , s : str ) -> str :
32
- if s == '':
33
- return ' '
34
- cache = collections.OrderedDict()
38
+ counter = collections.Counter()
39
+ for c in s:
40
+ counter[c] += 1
35
41
for c in s:
36
- cache[c] = 1 if cache.get(c) is None else cache[c] + 1
37
- for k, v in cache.items():
38
- if v == 1:
39
- return k
42
+ if counter[c] == 1 :
43
+ return c
40
44
return ' '
41
- ````
45
+ ```
42
46
43
47
### ** Java**
44
48
45
49
``` java
46
50
class Solution {
47
51
public char firstUniqChar (String s ) {
48
- if (" " . equals(s)) {
49
- return ' ' ;
50
- }
51
- Map<Character , Integer > map = new LinkedHashMap<> ();
52
- char [] chars = s. toCharArray();
53
- for (char c : chars) {
54
- map. put(c, map. get(c) == null ? 1 : 1 + map. get(c));
52
+ int n;
53
+ if ((n = s. length()) == 0 ) return ' ' ;
54
+ int [] counter = new int [26 ];
55
+ for (int i = 0 ; i < n; ++ i) {
56
+ int index = s. charAt(i) - ' a' ;
57
+ ++ counter[index];
55
58
}
56
- for (Map . Entry<Character , Integer > entry : map. entrySet()) {
57
- if (entry. getValue() == 1 ) {
58
- return entry. getKey();
59
- }
59
+ for (int i = 0 ; i < n; ++ i) {
60
+ int index = s. charAt(i) - ' a' ;
61
+ if (counter[index] == 1 ) return s. charAt(i);
60
62
}
61
63
return ' ' ;
62
64
}
@@ -71,13 +73,15 @@ class Solution {
71
73
* @return {character}
72
74
*/
73
75
var firstUniqChar = function (s ) {
74
- let t = new Array (26 ).fill (0 );
75
- let code = " a" .charCodeAt ();
76
- for (let i = 0 ; i < s .length ; i++ ) {
77
- t[s[i].charCodeAt () - code]++ ;
76
+ if (s .length == 0 ) return " " ;
77
+ let counter = new Array (26 ).fill (0 );
78
+ for (let i = 0 ; i < s .length ; ++ i) {
79
+ const index = s[i].charCodeAt () - " a" .charCodeAt ();
80
+ ++ counter[index];
78
81
}
79
- for (let i = 0 ; i < s .length ; i++ ) {
80
- if (t[s[i].charCodeAt () - code] === 1 ) return s[i];
82
+ for (let i = 0 ; i < s .length ; ++ i) {
83
+ const index = s[i].charCodeAt () - " a" .charCodeAt ();
84
+ if (counter[index] == 1 ) return s[i];
81
85
}
82
86
return " " ;
83
87
};
0 commit comments