problem
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”.
solution
方法一
思路过程
第一次看错题题意了,( ̄ε(# ̄)
字符串J中的这些字母代表宝石
字符串S中代表你有的石头
求的就是再你有得石头中有多少得宝石
第一个想法就是burte force(暴力搜索),直接把S中所有都遍历一次,看是不是J中有的
这里,不知道python和Java提供的字符串操作背后的效率是怎样的(见下面的知识总结)如果是线性的,建议改为python的集合或则java的hash
知识总结
What’s a faster operation, re.match/search or str.find?
这个问题链接说明了python中查找中in相对于find和match是最快的
并且 in的查找效率是依据后面可迭代的数据而定的
-
list - Average: O(n)
-
set/dict - Average: O(1), Worst: O(n)
-
在python中,对于in在字符串中,是sublinear(次线性的),算法是在原来的KPM algorithm改进,可以阅读这个问题解答
Python string ‘in’ operator implementation algorithm and time complexity -
java的indexof:
O(n+m) average and O(n*m) worst case.
代码
python
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
count=0
for i in S:
if i in J:
count+=1
return count
Java
class Solution {
public int numJewelsInStones(String J, String S) {
int count = 0;
for (int i = 0; i < S.length(); ++i) {
if (J.indexOf(S.charAt(i)) != -1) {
count++;
}
}
return count;
}
}
方法二
思路
变成hash查找,在效率上会提升
代码
python
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
J=set(J)
count=0
for i in S:
if i in J:
count+=1
return count
Java
class Solution {
public int numJewelsInStones(String J, String S) {
int count = 0;
Set<Character> hashset = new HashSet<>();
for (char c : J.toCharArray()) {
hashset.add(c);
}
for (char c : S.toCharArray()) {
if (hashset.contains(c)) {
++count;
}
}
return count;
}
}
方法三
思路
就是用背后的库,遍历J中每一个字符,再S中查找并计数
代码
python
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
count=0
for i in J:
count+=S.count(i)
return count
后续想法
-
其实,更加深层一点就是可以比较两个字符串的长度,如果查找更快,用多的字符串查找,少的字符串遍历,只是猜测
-
当然还可以试试先把S优化,把没用的重复的先给去除掉,这个我暂时没想出什么好的点子,如果看到的读者有方法的话,可以留言交流呀 谢啦!!☆⌒(*^-゜)v