771. 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 and J will consist of letters and have length at most 50.
The characters in J are distinct.
解法:
使用hash的方法,建立一个以ASCII码为key值的hashTable,首先扫描字符串J,将J中每个出现的字符对应的hashTable值置1;然后扫描字符串S,对于S中的每个字符串,在hashTable中使用字符对应的ASCII码进行查询,如果对应的hashTable值为1,则总数量加一。
这里又发现的一个小问题,对于memset的使用,使用memset初始化小块内存时,比for和while循环要快一些而且代码简洁,但是之前写成memset(hashTable,0,256),容易出错,因为后面的表大小的参数(例如256)是以字节为单位,所以,对于int或其他的就并不是都乘默认的1(字符型)了。而且不同的机器上int的大小也可能不同,所以最好用sizeof()。写成memset(hashTable,0,256*sizeof(int))。
void * memset ( void * ptr, int value, size_t num );
memset是对字节进行操作的,而且是依靠二进制进行初始化,比如,int是4个字节,memset把每个字节都赋值,也就是说,比如memset(a,2,sizeof(a))
则00000010 00000010 00000010 00000010,换算成十进制就变成16843009,
而0,则是00000000 00000000 00000000 00000000结果是0
而-1,则是11111111 11111111 11111111 11111111结果也是-1
所以memset对于int数组只能初始化为0或者-1。
class Solution {
public:
int numJewelsInStones(string J, string S) {
int hashTable[256];
memset(hashTable,0,256*sizeof(int));
for(int i =0;i < J.size() && J[i] != '\0';i++)
{
hashTable[J[i]]++;
}
int count = 0;
for(int i = 0;i < S.size() && S[i] != '\0';i++)
{
if(hashTable[S[i]] == 1)
count++;
}
return count;
}
};