題目地址:
https://www.lintcode.com/problem/jewels-and-stones/description
給定一個字符串,題目保證中字符兩兩不同;再給定一個字符串,問中有多少個字符在中出現過,重複次數也要計算。
用哈希表記錄裏有哪些字符,然後遍歷並統計即可。代碼如下:
import java.util.HashSet;
import java.util.Set;
public class Solution {
/**
* @param J: the types of stones that are jewels
* @param S: representing the stones you have
* @return: how many of the stones you have are also jewels
*/
public int numJewelsInStones(String J, String S) {
// Write your code here
Set<Character> set = new HashSet<>();
for (int i = 0; i < J.length(); i++) {
set.add(J.charAt(i));
}
int res = 0;
for (int i = 0; i < S.length(); i++) {
if (set.contains(S.charAt(i))) {
res++;
}
}
return res;
}
}
時空複雜度。