题目描述:

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 and J will consist of letters and have length at most 50.
  • The characters in J are distinct.

要完成的函数:

int numJewelsInStones(string J, string S)

说明:

1、给定两个字符串,字符串中的所有字符都代表石头种类,其中J字符串中的石头种类是玉石,S字符串中的石头种类是你已有的石头种类。要求根据J字符串判断你已有的石头中有多少是玉石,返回玉石的个数。字符大小写敏感。

2、这道题很容易,暴力解法就是双重循环,时间复杂度是O(n^2),我们也可以通过增加空间复杂度,建立哈希表,来降低时间复杂度。

代码如下:

    int numJewelsInStones(string J, string S)
{
unordered_set<char>set1(J.begin(),J.end());//转换为set存储
int i=0,s1=S.size(),count=0;
while(i<s1)
{
count+=set1.count(S[i]);//如果S[i]代表的石头是玉石,那么count+=1
i++;
}
return count;
}

上述代码实测9ms,beats 79.34% of cpp submissions。

最新文章

  1. ActionContext.getContext().getSession()
  2. ASP.NET Core 中文文档 第四章 MVC(01)ASP.NET Core MVC 概览
  3. Node.js API 初解读(二)
  4. Single Number
  5. php的特性
  6. Ubuntu 14.10 下grep命令详解
  7. pspo
  8. __dict__和__slots__
  9. Linux下Nginx+Tomcat整合的安装与配置
  10. baiduMap 显示所有的marker(在视野里显示所有的)
  11. 【SignalR学习系列】8. SignalR Hubs Api 详解(.Net C# 客户端)
  12. MongoDB 分布式架构 复制 分片 适用性范围
  13. Codeforces Round #432 Div. 1
  14. OpenDayLight——HelloWorld
  15. 使用RStudio远程连接MySQL
  16. VS一些快捷键
  17. postman添加cookie
  18. Android sync adapter初体验之为什么官方文档上的代码不能work
  19. delphi黑色背景模式
  20. 【快速查阅】Linux下启动和关闭Weblogic(管理服务器+被管服务器)

热门文章

  1. 微软人工智能公开课 https://mva.microsoft.com/colleges/microsoftai#!jobf=Developer
  2. spring之IOC容器创建对象
  3. [C++] the pointer array &amp; the array&#39;s pointer
  4. HttpClient 上传/下载文件计算文件传输进度
  5. docker镜像存出与载入
  6. C#编程之程序集和反射
  7. Java Decompiler(Java反编译工具)
  8. 设置emacs启动窗口的两种方法
  9. unity小记
  10. 简述各大 Linux 发行版,有主观,不完全,望见谅