1. 解法1
(遍历比较,时间复杂度O(J*S),空间复杂度O(1))
1.1 C#代码
public class Solution
{
public int NumJewelsInStones(string J, string S)
{
int Jlen = J.Length;
int Slen = S.Length;
int count = 0;
for(int i=0; i<Jlen;i++)
{
for(int j=0;j<Slen;j++)
{
if(S[j] == J[i])
++count;
}
}
return count;
}
}
1.2 Python3 代码
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
count = 0
for j in J:
for s in S:
if j == s:
count += 1
return count

本文介绍了一种通过遍历比较的方式实现的简单算法,用于计算字符串S中有多少字符出现在字符串J中,即统计石头中宝石的数量。该算法的时间复杂度为O(J*S),空间复杂度为O(1)。提供了C#和Python3两种语言的实现代码。
444

被折叠的 条评论
为什么被折叠?



