[Leetcode xx]格式备份 format
Posted leetcode刷题中
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode xx]格式备份 format相关的知识,希望对你有一定的参考价值。
【题目】
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"
.
两个集合A、B。A中是石头,B中是宝石。通过比对返回石头A中是宝石的个数。
【思路】
string转换外char数组,把原始数据存在HashSet中,通过比较键值,是否contains了B中的元素来控制ans++
【代码】
class Solution { public int numJewelsInStones(String J, String S) { char[] js=J.toCharArray(); char[] ss=S.toCharArray(); Set data=new HashSet(); int ans=0; //加入数据 for(char j:js){ data.add(j);} //遍历是否相等 for(char s:ss){ if(data.contains(s)) ans++; } return ans; } }
【参考】
以上是关于[Leetcode xx]格式备份 format的主要内容,如果未能解决你的问题,请参考以下文章