Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a5f0bc1

Browse files
🐱(string): 771. 宝石与石头
1 parent ab8ad7c commit a5f0bc1

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

‎docs/data-structure/string/README.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1423,6 +1423,49 @@ class Solution(object):
14231423
return result
14241424
```
14251425

1426+
## 771. 宝石与石头
1427+
1428+
[原题链接](https://leetcode-cn.com/problems/jewels-and-stones/)
1429+
1430+
### 解法一:遍历字符串
1431+
1432+
遍历字符串,寻找 S 中存在于 J 中的字母个数。
1433+
1434+
```python
1435+
class Solution:
1436+
def numJewelsInStones(self, J: str, S: str) -> int:
1437+
res = 0
1438+
for j in J:
1439+
for s in S:
1440+
if j == s:
1441+
res += 1
1442+
return res
1443+
```
1444+
1445+
pythonic 一点:
1446+
1447+
```python
1448+
class Solution:
1449+
def numJewelsInStones(self, J: str, S: str) -> int:
1450+
return len([x for x in S if x in J])
1451+
```
1452+
1453+
### 解法二:哈希表
1454+
1455+
记录 `S` 中每个字母出现的次数,再把 `J` 中存在的字母次数都相加。
1456+
1457+
```python
1458+
class Solution:
1459+
def numJewelsInStones(self, J: str, S: str) -> int:
1460+
s_count = dict()
1461+
for s in S:
1462+
s_count[s] = s_count.get(s, 0) + 1
1463+
res = 0
1464+
for j in J:
1465+
res += s_count.get(j, 0)
1466+
return res
1467+
```
1468+
14261469
## 1108. IP 地址无效化
14271470

14281471
[原题链接](https://leetcode-cn.com/problems/defanging-an-ip-address/)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /