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 61e3d9e

Browse files
Merge pull request MisterBooo#61 from chilimyan/master
0771 Solved
2 parents 60e0ab0 + d6c6cc7 commit 61e3d9e

File tree

4 files changed

+76
-0
lines changed

4 files changed

+76
-0
lines changed

‎0771-Jewels-Stones/Animation/1.mp4‎

1.83 MB
Binary file not shown.
7.48 MB
Loading[フレーム]
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# LeetCode 第 771 号问题:宝石与石头
2+
3+
> 本文首发于公众号「图解面试算法」,是 [图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>) 系列文章之一。
4+
>
5+
> 同步博客:https://www.algomooc.com
6+
7+
题目来源于LeetCode上第771号问题:宝石与石头。题目难度为Easy,目前通过率82.3%。
8+
9+
#### 题目描述
10+
11+
> 给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。
12+
>
13+
14+
```java
15+
示例 1:
16+
17+
输入: J = "aA", S = "aAAbbbb"
18+
输出: 3
19+
示例 2:
20+
21+
输入: J = "z", S = "ZZ"
22+
输出: 0
23+
注意:
24+
S 和 J 最多含有50个字母。
25+
J 中的字符不重复。
26+
```
27+
28+
#### 题目解析
29+
30+
这道题目中有宝石,石头,看起来高大上似的。其实是比较简单的,大致意思就是给定一串字符J和另一串字符S,求J中每个字符出现在S字符串中的次数。比较好的解法是先将J字符串中字符放进哈希集合中,然后把S中每个字符依次去判断是否包含在哈希集合中。我刷了不少LeetCode题,总结一点就是:当你看懂题目基本上就成功了一半。
31+
32+
#### 动画理解
33+
34+
![](../Animation/Animation.gif)
35+
36+
#### 代码实现
37+
38+
Java语言
39+
40+
```java
41+
class Solution {
42+
public int numJewelsInStones(String J, String S) {
43+
Set<Character> Jset = new HashSet();
44+
for (char j: J.toCharArray())
45+
Jset.add(j);
46+
47+
int ans = 0;
48+
for (char s: S.toCharArray())
49+
if (Jset.contains(s))
50+
ans++;
51+
return ans;
52+
}
53+
}
54+
```
55+
56+
#### 复杂度分析
57+
58+
+ 时间复杂度:O(J.length+S.length),O(J.length) 这部分来自于创建J,O(S.length) 这部分来自于搜索 S。
59+
+ 空间复杂度:O(J.length)
60+
61+
62+

‎0771-Jewels-Stones/Code/1.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
2+
class Solution {
3+
public int numJewelsInStones(String J, String S) {
4+
Set<Character> Jset = new HashSet();
5+
for (char j: J.toCharArray())
6+
Jset.add(j);
7+
8+
int ans = 0;
9+
for (char s: S.toCharArray())
10+
if (Jset.contains(s))
11+
ans++;
12+
return ans;
13+
}
14+
}

0 commit comments

Comments
(0)

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