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.
中文版
给定字符串J
代表石头中宝石的类型,和字符串 S
代表你拥有的石头。 S
中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
J
中的字母不重复,J
和 S
中的所有字符都是字母。字母区分大小写,因此"a"
和"A"
是不同类型的石头。
以下代码基于 jdk 1.8
解法一
反正宝石列表中的字母不重复,直接暴力循环判断相等
时间复杂度 O(s*j)
public int numJewelsInStones(String J, String S) {
int num = 0;
char[] js = J.toCharArray();
char[] ss = S.toCharArray();
for (int i=0;i<js.length;i++){
for (int j = 0; j < ss.length; j++) {
if (js[i] == ss[j]){
num++;
}
}
}
return num;
}
提交结果如下:
Runtime: 1 ms, faster than 98.29% of Java online submissions for Jewels and Stones.
Memory Usage: 33.9 MB, less than 100.00% of Java online submissions for Jewels and Stones.
public char[] toCharArray() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length);
return result;
}
来波小优化,稍微看下以上 toCharArray() 方法的实现,就会发现里面是进行了一次数组的拷贝,所以效率稍慢,而基于下面两点
1、indexOf() 方法直接遍历String类内部的字符数组,而不用经过数组拷贝
2、J中的元素不重复,所以可对每块石头进行判断,判断其是不是宝石,如果属于宝石,就可直接 break
解法二
public int numJewelsInStones(String J, String S) {
int num = 0;
char[] ss = S.toCharArray();
for (int i=0;i<ss.length;i++){
if (J.indexOf(ss[i]) > -1){
num++;
}
}
return num;
}
提交结果如下:
Runtime: 0 ms, faster than 100.00% of Java online submissions for Jewels and Stones.
Memory Usage: 33.6 MB, less than 100.00% of Java online submissions for Jewels and Stones.
然而以上两个其实都差不多,基本是一样的,没啥意思 ……
再看下题目,其实发现就是个多次查找的过程,而想想查找里时间复杂度最低的,估计就是哈希表了,所以直接用HashSet,先存入所有宝石类型字符,然后对所有石头字符,依次计算其 hashCode,直接判断其是不是宝石即可,代码如下,时间复杂度O(m+n) 吧
解法三
public int numJewelsInStones(String J, String S) {
int num = 0;
Set set = new HashSet();
for (char c:J.toCharArray()){
set.add(c);
}
for (char s:S.toCharArray()){
if (set.contains(s))
num++;
}
return num;
}
运行结果如下,时间上倒是慢了好多,估计是所给字符串长度均较短,还有方法内部原因吧
Runtime: 2 ms, faster than 69.41% of Java online submissions for Jewels and Stones.
Memory Usage: 33.8 MB, less than 100.00% of Java online submissions for Jewels and Stones.