Description
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 character in
J
are distinct.
My Submission
int numJewelsInStones(char* J, char* S) {
int num = 0;
for(int i = 0; i<strlen(J); i++)
for(int j = 0; j<strlen(S); j++)
{
if(J[i] == S[j])
num++;
}
return num;
}
解题思路:
首先想到使用两层嵌套循环,外层为J,内层为S,遍历S中元素j依次和J的i个元素比较,若相等则计数器加一,最后返回计数器。
遇到问题:
刚开始不知道C字符串长度的计算方法,经查阅百度得知可以使用strlen()
函数。同时有一个疑问,不清楚指针和数组名是否可以进行同等操作,现在想来应该是一样的。
Sample Submission
sample 0 ms submission:
int numJewelsInStones(char* J, char* S) {
int result_num = 0;
char* src = J;
char* dst = S;
int i,j;
if ((J == NULL) || (S = NULL))
return -1;
for (i=0;i<50;i++)
{
if (src[i] == '\0')
break;
for (j=0;j<50;j++)
{
if (dst[j] == '\0')
break;
if (src[i] == dst[j]) {
//printf("test %c:%c\n", src[i], dst[j]);
result_num++;
}
}
}
return result_num;
}
sample 7880 kb submission:
int numJewelsInStones(char* J, char* S) {
bool hash[53]={0};
while(*J)
{
if(*J<='z' && *J>='a' )
hash[(unsigned)((*J)-'a')]=true;
else
hash[(unsigned)((*J)-'A'+26)]=true;
J++;
}
int count = 0;
while(*S)
{
if(*S<='z' && *S>='a' && hash[(unsigned)((*S)-'a')])
count++;
if(*S<='Z' && *S>='A' && hash[(unsigned)((*S)-'A')+26])
count++;
S++;
}
return count;
}