中国建设银行招标网站,公司二次开发好吗,购物类网站开发,广告设计公司任务书【LetMeFly】771.宝石与石头
力扣题目链接#xff1a;https://leetcode.cn/problems/jewels-and-stones/ 给你一个字符串 jewels 代表石头中宝石的类型#xff0c;另有一个字符串 stones 代表你拥有的石头。 stones 中每个字符代表了一种你拥有的石头的类型#xff0c;你想…【LetMeFly】771.宝石与石头
力扣题目链接https://leetcode.cn/problems/jewels-and-stones/ 给你一个字符串 jewels 代表石头中宝石的类型另有一个字符串 stones 代表你拥有的石头。 stones 中每个字符代表了一种你拥有的石头的类型你想知道你拥有的石头中有多少是宝石。
字母区分大小写因此 a 和 A 是不同类型的石头。 示例 1
输入jewels aA, stones aAAbbbb
输出3示例 2
输入jewels z, stones ZZ
输出0提示
1 jewels.length, stones.length 50jewels 和 stones 仅由英文字母组成jewels 中的所有字符都是 唯一的
方法一统计
对于无法直接判断一个字符是否在字符串中出现过的编程语言可以写一个返回值为布尔类型的函数来实现上述功能。
bool isIn(char c, string s) {for (char _ : s) {if (c _) {return true;}}return false;
}接着我们只需要遍历stones字符串并统计在jewels中出现过的字符个数就行了。
时间复杂度 O ( l e n ( j e w e l s ) × l e n ( s t o n e s ) ) O(len(jewels)\times len(stones)) O(len(jewels)×len(stones))空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C
class Solution {
private:bool isIn(char c, string s) {for (char _ : s) {if (c _) {return true;}}return false;}
public:int numJewelsInStones(string jewels, string stones) {int ans 0;for (char stone : stones) {ans isIn(stone, jewels);}return ans;}
};Python
class Solution:def numJewelsInStones(self, jewels: str, stones: str) - int:return sum(stone in jewels for stone in stones)それわ, steins;gate! 同步发文于CSDN原创不易转载请附上原文链接哦~ Tisfyhttps://letmefly.blog.csdn.net/article/details/131888350