LeetCode 771 Jewels and Stones
(本人专注于刷leetcode全部题c#语言算法,后期发视频教程)
相信有些人看到这道题目的时候不会一下子明白。
首先解释一下题意:
理解/核心: J 中字符 在 S 中出现的次数,区分大小写。
题目:
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: 解释:a字母出现在S的字符串中的次数为1,A 出现在S字符串的次数为2 . 1+2=3的问题!!!!
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2: 解释:z在S中出现了0次,结果为0,原因:区分大小写。(读懂了题目就简单了)
Input: J = "z", S = "ZZ"
Output: 0
c#版本答案:(未考虑时间复杂度,较为理解)
static void Main(string[] args)
{
string J = "zZsu";
string P = "zZZasuidassssssss";
int pc = GetNum(J, P);
Console.WriteLine(pc);
Console.ReadKey();
}
public static int GetNum(string J,string P)
{
int num = 0;
for (int i = 0; i < P.Length; i++)
{
for (int j = 0; j < J.Length; j++)
{
if (J[j] == P[i])
{
num++;
}
}
}
return num;
}
c#版本答案:(考虑空间复杂度的算法)
int[]count =new int[64];
char[] ooo= J.ToCharArray();
for (char c=' ' ; c < J.ToCharArray().Length; c++)
{
count[c - 'A']++;
}
int ans = 0;
for (char c =' '; c < P.ToCharArray().Length; c++)
{
if (count[c - 'A'] >= 1)
ans++;
}
return ans;
如果对答案有异议,欢迎各路大神指点,并在评论区留下c#代码,相互学习。
最后是hashtable的方法:
#region 771. 宝石与石头
private static int GetBS(string J, string S)
{
int res = 0;
//1、将宝石添加到hashtable 里
char[] ch = J.ToCharArray();
Hashtable hs = new Hashtable();
for (int i = 0; i < ch.Length; i++)
{
hs.Add(ch[i],i);
}
//2、判断hashtable 是否包含
char[] chs = S.ToCharArray();
for (int i = 0; i < chs.Length; i++)
{
if (hs.ContainsKey(chs[i]))
{
res++;
}
}
return res;
}
#endregion
方法四;
Just one Line and Beat 99% C# Code:
return S.Count(c => J.Contains(c));