zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    RegExp实例
    Date类型之组件方法
    Date类型之继承方法
    数组常见方法下
    Math对象
    数组常见方法上
    CSS变量
    基本类型和引用类型
    Python习题集(十五)
    Python习题集(十四)
  • 原文地址:https://www.cnblogs.com/sheepcore/p/12394816.html
Copyright © 2011-2022 走看看