[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

宝石与石头。给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。思路是用hashset记录J中的字符,然后去S中看是否有重复的。

时间O(m + n)

空间O(n)

Java实现

 1 class Solution {
 2     public int numJewelsInStones(String J, String S) {
 3         int res = 0;
 4         Set<Character> set = new HashSet<>();
 5         for (char j : J.toCharArray()) {
 6             set.add(j);
 7         }
 8         for (char s : S.toCharArray()) {
 9             if (set.contains(s)) {
10                 res++;
11             }
12         }
13         return res;
14     }
15 }

 

discussion中有人给出了这样的解法,注意这种解法的时间复杂度更高,是O(mn)。因为string.contains()这个函数的复杂度是O(n)。

 1 class Solution {
 2     public static int numJewelsInStones(String j, String s) {
 3         int count = 0;
 4         for (char c : s.toCharArray()) {
 5             if (j.contains(c + ""))
 6                 count++;
 7         }
 8         return count;
 9     }
10 }

 

LeetCode 题目总结

posted @ 2020-05-03 07:16  CNoodle  阅读(173)  评论(0编辑  收藏  举报