leetcode chicken dish wits series (3) --- Jewels and Stones jewelry and diamonds

1. Original title:

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".

 

Paraphrase translation: J is a string, it represents those who are considered the type of diamond you want . For example, J = ad, it means a and d can be considered as two diamonds you want jewelry.

And S is a string, it represents all of your diamond. For example S = aAfdd, it means that a total of four different types of diamond (note case sensitive), and d has two such diamonds.

You need to write a program to know that you want a total of several diamond in the presence of several S inside.

 

2. Problem-solving ideas:

This question is the idea very much. This question is because in theory, you want to do it basically no brain, direct scanning to write a for loop to get away, but then the code is very slow also eat memory.

So most people's attention is focused on how to reduce the time and space complexity.

It is recommended to take a look at the discussion area, there are numerous kinds of ideas, but I personally like to choose the method here.

. A need of knowledge:

In order to minimize the time complexity, leetcode Gangster used unorder set (this data structure based on a hash table), this data structure is easy to view, add, and delete, but more so because of the disorder take up memory, but considering that we the purpose does not require the sort of times, so no problem.

Reference reading: http://www.cplusplus.com/reference/unordered_set/unordered_set/

 

. B problem-solving ideas:

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;
}
};

The core is unorder set. We create a unorder set to store the J char (J main role is as a query)

Then go with char s S a representative species which is to compare the for loop inside J type, if found inside res added, the final output, in fact, is to find the most suitable data structure.

Guess you like

Origin www.cnblogs.com/cptCarlvon/p/12053084.html