LeetCode-771 Jewels and Stones Solution with Java
Posted sheepcore
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-771 Jewels and Stones Solution with Java相关的知识,希望对你有一定的参考价值。
1. Description:
Notes:
2. Examples:
3.Solutions:
Version 1: hashmap
1 /** 2 * Created by sheepcore on 2020-03-02 3 * @param J 4 * @param S 5 * @return the numbers of jewels in stones 6 */ 7 public int numJewelsInStones(String J, String S) { 8 Map<Character, Integer> jewels = new HashMap<>(); 9 int check; 10 for (char c : J.toCharArray()) 11 if (!jewels.containsKey(c)) 12 jewels.put(c, 0); 13 14 for (char c: S.toCharArray()) 15 if (jewels.containsKey(c)) 16 jewels.put(c, jewels.get(c) + 1); 17 18 Collection<Integer> values = jewels.values(); 19 int sum = 0; 20 for(int val : values) { 21 sum += val; 22 } 23 return sum; 24 }
Version 1: for-loop
1 public int numJewelsInStones(String J, String S) { 2 int num = 0; 3 for (int i = 0; i < S.length(); i++) { 4 if (J.contains(S.charAt(i) + "")) 5 num++; 6 } 7 return num; 8 }
以上是关于LeetCode-771 Jewels and Stones Solution with Java的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 771:Jewels and Stones
LeetCode 771. Jewels and Stones
[LeetCode] 771. Jewels and Stones 珠宝和石头
[leetcode-771-Jewels and Stones]