博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode讲解--771. Jewels and Stones
阅读量:6933 次
发布时间:2019-06-27

本文共 1166 字,大约阅读时间需要 3 分钟。

771. Jewels and Stones

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.

看到这个题目首先想到的是要避免过多的循环,这是一个典型的查找类型的题。

最简单最直觉的算法是,每次从J中取出一个字符,然后遍历一遍S,如果找到,就对返回结果+1

但这样的算法复杂度是:O(m*n)

我们可以把J当做一个字典,然后遍历S,看看其中的字符是否在字典内。这样就只需要遍历一遍了。

Java代码

class Solution {    public int numJewelsInStones(String J, String S) {        int result=0;        Map
JMap = new HashMap<>(); for(Character c:J.toCharArray()){ JMap.put(c, 0); } for(Character c:S.toCharArray()){ Integer count = JMap.get(c); if(count!=null){ result++; } } return result; }}

转载地址:http://lnwnl.baihongyu.com/

你可能感兴趣的文章
ios中打包
查看>>
Github+Gitlb的使用
查看>>
单目+惯性 VIO SLAM 对比
查看>>
Apress水果大餐——移动开发
查看>>
Emmet:HTML/CSS代码快速编写规范(转发)
查看>>
openssl——初了解
查看>>
javax.swing.jFrame
查看>>
Testing tools
查看>>
iOS开发UI篇—Quartz2D使用(绘制基本图形)
查看>>
Zabbix邮件报警设置方法
查看>>
总结:实例化SqlParameter时,如果是字符型,一定要指定size属性,还有制定具体的类型...
查看>>
蓝桥杯练习系统算法训练习题加答案java版本
查看>>
Java&Xml教程(六)使用JDOM解析XML文件
查看>>
2018.8.17提高B组模拟考试
查看>>
c#获取电脑硬件信息参数说明(主板篇 Win32_BaseBoard )
查看>>
高性能Mysql主从架构的复制原理及配置详解
查看>>
【leetcode】944. Delete Columns to Make Sorted
查看>>
thinkphp 查找表并返回结果
查看>>
MySQL应用
查看>>
Android--百度地图密钥申请+环境配置(一)
查看>>