当前位置: 代码迷 >> 综合 >> 771.宝石与石头(LeetCode)---java实现
  详细解决方案

771.宝石与石头(LeetCode)---java实现

热度:66   发布时间:2024-01-24 10:29:27.0

算法思路:

1、通过Hash表将J中的字符串分割,每个字符作为一个子字符串,以子字符串为键,索引作为值,映射成对应的键值对

2、遍历S中的字符串,查找每个子字符串是否能在J对应的HashMap中找到非空值,找到一个则表示此字符在J中出现过,相应的计数器加1

class Solution {public int numJewelsInStones(String J, String S) {Map<String,Integer> map = new HashMap<String,Integer>();int len = J.length();    for(int j=0;j<len;++j){String temp=J.substring(j,j+1);map.put(temp,j);}int size=S.length();int cnt=0;for(int j=0;j<size;++j){String temp=S.substring(j,j+1);if(map.get(temp)!=null){cnt++;}}return cnt;}
}