LeetCode 771. Jewels and Stones

Posted 逆風的薔薇

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 771. Jewels and Stones相关的知识,希望对你有一定的参考价值。

题目

You're given strings J representing the types of stones that are jewels, and S representing the stones you have.  Each character in S is a type of stone you have.  You want to know how many of the stones you have are also jewels.

The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".

Example 1:

Input: J = "aA", S = "aAAbbbb"
Output: 3

Example 2:

Input: J = "z", S = "ZZ"
Output: 0

Note:

  • S and J will consist of letters and have length at most 50.
  • The characters in J are distinct.

分析

字符串J:存储不重复出现的key

字符串S:有重复值的value

计算S中出现几个key。

暴力法:二重循环 O(m*n)

优化:哈希 O(m+n)

代码

class Solution 
    // Solution I O(m*n)
    /*
    public int numJewelsInStones(String J, String S) 
        int result = 0;
        for (char c : J.toCharArray()) 
            result += countOfLetters(c, S);
        
        return result;
    
    
    public int countOfLetters(char c, String S) 
        int count = 0;
        for (char ch : S.toCharArray()) 
            if (ch == c) 
                ++count;
            
        
        
        return count;
    
    */
    
    // Solution II O(m+n)
    /*public int numJewelsInStones(String J, String S) 
        int count = 0;

        Set<Character> setJ = new HashSet<Character>();
        for (char c : J.toCharArray()) 
            setJ.add(c);
        

        for (char c : S.toCharArray()) 
            count += setJ.contains(c) ? 1 : 0;
        

        return count;
    */

    // Solution III O(m*n)
    public int numJewelsInStones(String J, String S) 
        int result = 0;
        for (char c : S.toCharArray()) 
            result += J.indexOf(c) == -1 ? 0 : 1;
        
        return result;
    

 

以上是关于LeetCode 771. Jewels and Stones的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 771. Jewels and Stones

[leetcode-771-Jewels and Stones]

Leetcode #771. Jewels and Stones

[LeetCode&Python] Problem 771: Jewels and Stones

[LeetCode] 771. Jewels and Stones 珠宝和石头

LeetCode 771:Jewels and Stones