Skip to content

Commit 0aadba7

Browse files
committed
feat: add python and java solutions to lcof problem
添加《剑指 Offer》题解:面试题50. 第一个只出现一次的字符
1 parent c50f10e commit 0aadba7

File tree

3 files changed

+96
-0
lines changed

3 files changed

+96
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# [面试题50. 第一个只出现一次的字符](https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/)
2+
3+
## 题目描述
4+
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。
5+
6+
**示例:**
7+
8+
```
9+
s = "abaccdeff"
10+
返回 "b"
11+
12+
s = ""
13+
返回 " "
14+
``` 
15+
16+
**限制:**
17+
18+
- `0 <= s 的长度 <= 50000`
19+
20+
## 解法
21+
有序字典解决。
22+
23+
### Python3
24+
```python
25+
import collections
26+
27+
class Solution:
28+
def firstUniqChar(self, s: str) -> str:
29+
if s == '':
30+
return ' '
31+
cache = collections.OrderedDict()
32+
for c in s:
33+
cache[c] = 1 if cache.get(c) is None else cache[c] + 1
34+
for k, v in cache.items():
35+
if v == 1:
36+
return k
37+
return ' '
38+
```
39+
40+
### Java
41+
```java
42+
class Solution {
43+
public char firstUniqChar(String s) {
44+
if ("".equals(s)) {
45+
return ' ';
46+
}
47+
Map<Character, Integer> map = new LinkedHashMap<>();
48+
char[] chars = s.toCharArray();
49+
for (char c : chars) {
50+
map.put(c, map.get(c) == null ? 1 : 1 + map.get(c));
51+
}
52+
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
53+
if (entry.getValue() == 1) {
54+
return entry.getKey();
55+
}
56+
}
57+
return ' ';
58+
}
59+
}
60+
```
61+
62+
### ...
63+
```
64+
65+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public char firstUniqChar(String s) {
3+
if ("".equals(s)) {
4+
return ' ';
5+
}
6+
Map<Character, Integer> map = new LinkedHashMap<>();
7+
char[] chars = s.toCharArray();
8+
for (char c : chars) {
9+
map.put(c, map.get(c) == null ? 1 : 1 + map.get(c));
10+
}
11+
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
12+
if (entry.getValue() == 1) {
13+
return entry.getKey();
14+
}
15+
}
16+
return ' ';
17+
}
18+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import collections
2+
3+
class Solution:
4+
def firstUniqChar(self, s: str) -> str:
5+
if s == '':
6+
return ' '
7+
cache = collections.OrderedDict()
8+
for c in s:
9+
cache[c] = 1 if cache.get(c) is None else cache[c] + 1
10+
for k, v in cache.items():
11+
if v == 1:
12+
return k
13+
return ' '

0 commit comments

Comments
 (0)