文章目录
- 一【题目类别】
- 二【题目难度】
- 三【题目编号】
- 四【题目描述】
- 五【题目示例】
- 六【解题思路】
- 七【题目提示】
- 八【时间频度】
- 九【代码实现】
- 十【提交结果】
一【题目类别】
- 字符串
二【题目难度】
- 简单
三【题目编号】
- 771.宝石与石头
四【题目描述】
- 给你一个字符串 jewels 代表石头中宝石的类型,另有一个字符串 stones 代表你拥有的石头。 stones 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
- 字母区分大小写,因此 “a” 和 “A” 是不同类型的石头。
五【题目示例】
-
示例 1:
- 输入:jewels = “aA”, stones = “aAAbbbb”
- 输出:3
-
示例 2:
- 输入:jewels = “z”, stones = “ZZ”
- 输出:0
六【解题思路】
- 利用哈希表的思想,分别统计大写字母和小写字母的个数
- 然后遍历jewels字符串,累计对应字符的出现次数
- 最后返回结果即可
七【题目提示】
- 1 < = j e w e l s . l e n g t h , s t o n e s . l e n g t h < = 50 1 <= jewels.length, stones.length <= 50 1<=jewels.length,stones.length<=50
- j e w e l s 和 s t o n e s 仅 由 英 文 字 母 组 成 jewels 和 stones 仅由英文字母组成 jewels和stones仅由英文字母组成
- j e w e l s 中 的 所 有 字 符 都 是 唯 一 的 jewels 中的所有字符都是 唯一的 jewels中的所有字符都是唯一的
八【时间频度】
- 时间复杂度: O ( m a x ( m , n ) ) O(max(m,n)) O(max(m,n)),其中 m , n m,n m,n为两个输入字符串的长度
- 空间复杂度: O ( 1 ) O(1) O(1)
九【代码实现】
- Java语言版
package String;
/**
* @Author: IronmanJay
* @Description: 771.宝石与石头
* @CreateTime: 2022-11-29 09:23
*/
public class p771_JewelsAndStones {
public static void main(String[] args) {
String jewels = "aA";
String stones = "aAAbbbb";
int res = numJewelsInStones(jewels, stones);
System.out.println("res = " + res);
}
public static int numJewelsInStones(String jewels, String stones) {
int[] countSmall = new int[27];
int[] countBig = new int[27];
for (int i = 0; i < stones.length(); i++) {
char c = stones.charAt(i);
if (c >= 'a' && c <= 'z') {
countSmall[c - 'a']++;
} else {
countBig[c - 'A']++;
}
}
int res = 0;
for (int i = 0; i < jewels.length(); i++) {
char c = jewels.charAt(i);
if (c >= 'a' && c <= 'z') {
res += countSmall[c - 'a'];
} else {
res += countBig[c - 'A'];
}
}
return res;
}
}
- C语言版
#include<stdio.h>
#include<stdlib.h>
int numJewelsInStones(char * jewels, char * stones)
{
int* countSmall = (int*)calloc(27, sizeof(int));
int* countBig = (int*)calloc(27, sizeof(int));
for (int i = 0; i < strlen(stones); i++)
{
char c = stones[i];
if (c >= 'a' && c <= 'z')
{
countSmall[c - 'a']++;
}
else
{
countBig[c - 'A']++;
}
}
int res = 0;
for (int i = 0; i < strlen(jewels); i++)
{
char c = jewels[i];
if (c >= 'a' && c <= 'z')
{
res += countSmall[c - 'a'];
}
else
{
res += countBig[c - 'A'];
}
}
return res;
}
/*主函数省略*/
十【提交结果】
-
Java语言版
-
C语言版