leetcode菜鸡斗智斗勇系列(3)--- Jewels and Stones珠宝和钻石

1.原题:

https://leetcode.com/problems/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".

意译翻译:J是一个string,它代表的是那些被认为是你想要的的钻石种类。比如J=ad,那说明a和d这两种钻石可以被视为你想要的珠宝。

而S也是一个string,它代表的是你所有的钻石。比如S = aAfdd,那说明一共有4种不同的钻石(注意这里区分大小写),而d这种钻石有两个。

你需要写一个程序来得知你想要的这种几种钻石一共有几个存在在这个S里面。

2.解题思路:

这道题的思路非常多。因为这道题理论上讲,想要做出来基本上很无脑,直接写一个for loop扫描就完事了,但是那样的话代码很慢还吃内存。

因此大多数人的重点是关注如何降低时间和空间复杂度上。

建议去看看讨论区,里面有无数种思路,这里只选择我个人来说喜欢的方法。

a.需要的知识点:

为了最小化时间复杂度,leetcode大佬使用了unorder set(这个数据结构基于哈希表),这种数据结构就是方便查阅,增添和删除,但是因为无序所以更占用内存,不过考虑到我们这次的目的不需要排序,所以没问题。

参考阅读:http://www.cplusplus.com/reference/unordered_set/unordered_set/

b.解题思路:

class Solution {
public:
int numJewelsInStones(string J, string S) {
int res = 0;
unordered_set<char> setJ(J.begin(), J.end());
for (char s : S)
if (setJ.count(s))

res++;
return res;
}
};

核心就是unorder set.我们创建一个unorder set来储存J的char(因为J主要作用是查询)

然后用char s 去一个个代表S里面的种类的for loop来对比J里面的种类,如果找到就加进res里面,最后输出,其实就是要找到最合适的数据结构。

猜你喜欢

转载自www.cnblogs.com/cptCarlvon/p/12053084.html