771. Jewels and Stones
You're given strings J
representing the types of stones that are jewels, and S
representing the stones you have. Each character in S
is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J
are guaranteed distinct, and all characters in J
and S
are letters. Letters are case sensitive, so "a"
is considered a different type of stone from "A"
.
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
Note:
S
andJ
will consist of letters and have length at most 50.- The characters in
J
are distinct.
时间复杂度 O(mn)
题目已表示 J
中字母不会重复,就不用考虑循环对比重复计数的问题。所以一开始就想到时间复杂度 O(mn)。字符串字符和字符循环遍历比较。
public int numJewelsInStones(String J, String S) {
int num = 0;
for (int i = 0; i < J.length(); i++) {
for (int j = 0; j < S.length(); j++) {
if (J.charAt(i) == S.charAt(j)) {
num++;
}
}
}
return num;
}
上面方法有点傻的地方,比如 J
的第 1 位字母和 S
第 1 位字母相同,按理说 S
第 1 位字母就没有再比较的必要了。但是上面的方法是每个都比较一遍。
时间复杂度 O(m+n)
Explanation
- read
J
and build jewels hash set. - read
S
and count jewels.
Time complexity
I used hash set and it's O(1) to check if it contains an element.
So the total time complexity will be O(M+N), instead of O(MN)
public int numJewelsInStones(String J, String S) {
int res = 0;
Set setJ = new HashSet();
for (char j: J.toCharArray()) setJ.add(j);
for (char s: S.toCharArray()) if (setJ.contains(s)) res++;
return res;
}