771. 宝石与石头『简单』

题目来源于力扣(LeetCode

一、题目

771. 宝石与石头

题目相关标签:哈希表

说明:

  • SJ 最多含有50个字母。
  • J 中的字符不重复。

二、解题思路

2.1 哈希表——Set集合

  1. 遍历字符串 J,将字符添加到 Set 集合中

  2. 遍历字符串 S,若遍历的字符在 Set 集合中,则说明该字符在字符串 J 中存在,结果加 1

2.2 哈希表——哈希数组

  1. 定义哈希数组,长度为 58,在 ASCII 码中,从 'A' 到 'z' 的距离为 58

  2. 遍历字符串 J,将字符记录到哈希数组中

  3. 遍历字符串 S,若遍历的字符在哈希数组中标记不为 0,则说明该字符在字符串 J 中存在,结果加 1

三、代码实现

3.1 哈希表——Set集合

public static int numJewelsInStones(String J, String S) {
    Set<Character> set = new HashSet<>();
    int count = 0;

    for (int i = 0; i < J.length(); i++) {
        set.add(J.charAt(i));
    }
    for (int i = 0; i < S.length(); i++) {
        if (set.contains(S.charAt(i))) {
            count++;
        }
    }
    return count;
}

3.2 哈希表——哈希数组

public static int numJewelsInStones2(String J, String S) {
    // 空值判断与长度为 0 的判断
    if (null == J || J.isEmpty() || null == S || S.isEmpty()) {
        return 0;
    }
    // 定义 map 记录字符串 J 中的字符是否出现
    int[] arr = new int[58];

    char[] arrj = J.toCharArray();
    char[] arrs = S.toCharArray();
	
    for (char i : arrj) {
        arr[i - 'A'] ++;
    }

    int count = 0;
    for (char i : arrs) {
        if (arr[i - 'A'] == 1) {
            count++;
        }
    }
    return count;
}

四、执行用时

4.1 哈希表——Set集合

4.2 哈希表——哈希数组

五、部分测试用例

public static void main(String[] args) {
    String J = "aA", S = "aAAbbbb";  // output: 3
//    String J = "z", S = "ZZ";  // output: 0

    int result = numJewelsInStones(J, S);
    System.out.println(result);
}
原文地址:https://www.cnblogs.com/zhiyin1209/p/13257396.html