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.

 

解法一:BF

O(n2)

class Solution {
    public int numJewelsInStones(String J, String S) {
        int l1 = J.length();
        int l2 = S.length();
        int c = 0;
        for(int i=0; i<l2;i++) {
            for(int j=0; j<l1; j++){
                if(J.charAt(j) == S.charAt(i)) c++;
            }
        }
        return c;
    }
}

解法二:HashSet

O(M+N)

class Solution {
    public int numJewelsInStones(String J, String S) {
        int c = 0;
        Set<Character> setJ = new HashSet<>();
        for(char j: J.toCharArray()) setJ.add(j);
        for(char s: S.toCharArray()) {
            if(setJ.contains(s)) c++;
        }
        return c;
    }
}

 

posted @ 2019-01-28 20:54  JamieLiu  阅读(163)  评论(0编辑  收藏  举报