File tree 1 file changed +43
-0
lines changed
docs/data-structure/string
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -1423,6 +1423,49 @@ class Solution(object):
1423
1423
return result
1424
1424
```
1425
1425
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
+
1426
1469
## 1108. IP 地址无效化
1427
1470
1428
1471
[ 原题链接] ( https://leetcode-cn.com/problems/defanging-an-ip-address/ )
You can’t perform that action at this time.
0 commit comments