【力扣771】宝石与石头

题目描述:给你一个字符串 jewels 代表石头中宝石的类型,另有一个字符串 stones 代表你拥有的石头。 stones 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。字母区分大小写,因此 “a” 和 “A” 是不同类型的石头。

示例 1:

输入:jewels = “aA”, stones = “aAAbbbb” 输出:3

示例 2:

输入:jewels = “z”, stones = “ZZ” 输出:0

提示:

  1. 1 <= jewels.length, stones.length <= 50
  2. jewels 和 stones 仅由英文字母组成
  3. jewels 中的所有字符都是 唯一的

解题思路: 由题知,宝石的类型一定是不重复的,首先我们可以想到的是遍历字符串stones,对于stones中的每个字符,遍历一次字符串jewels。如果其和 jewels 中的某一个字符相同,则是宝石。

class Solution {
          
   
    public int numJewelsInStones(String jewels, String stones) {
          
   
        int jewelsCount = 0;
        int jewelsLength = jewels.length(), stonesLength = stones.length();
        for (int i = 0; i < stonesLength; i++) {
          
   
            char stone = stones.charAt(i);
            for (int j = 0; j < jewelsLength; j++) {
          
   
                char jewel = jewels.charAt(j);
                if (stone == jewel) {
          
   
                    jewelsCount++;
                    break;
                }
            }
        }
        return jewelsCount;
    }
}

此方法是我们常会想到的暴力遍历方法也是官方给的一种答案,但缺点是由于遍历的次数较多而导致时间复杂度较高,因此我们可以使用集合的方法来解答: 将J里的所有字符放在集合Set里面,遍历S看一下有没有J中相应的字符即可。

class Solution {
          
   
    public int numJewelsInStones(String jewels, String stones) {
          
   
        HashSet<Character> set = new HashSet<>();

        for(int i = 0; i < jewels.length();i++) {
          
   
            set.add(jewels.charAt(i));
        }
        int count = 0;
        for(char ch : stones.toCharArray()) {
          
   
            if(set.contains(ch)) {
          
   
                count++;
            }
        }
        return count;
    }
}
经验分享 程序员 微信小程序 职场和发展