[LeetCode] 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 Sis a type of stone you have.  You want to know how many of the stones you have are also jewels.html

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".ide

Example 1:post

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

Example 2:優化

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

Note:url

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

 

這道題給了咱們兩個字符串,珠寶字符串J和石頭字符串S,其中J中的每一個字符都是珠寶,S中的每一個字符都是石頭,問咱們S中有多少個珠寶。這道題沒什麼難度,高於八成的Accept率也應證了其Easy難度實至名歸。那麼先來暴力搜索吧,就將S中的每一個字符都在J中搜索一遍,搜索到了就break掉,參見代碼以下:spa

 

解法一:code

class Solution {
public:
    int numJewelsInStones(string J, string S) {
        int res = 0;
        for (char s : S) {
            for (char j : J) {
                if (s == j) {
                    ++res; break;
                }
            }
        }
        return res;
    }
};

 

咱們用HashSet來優化時間複雜度,將珠寶字符串J中的全部字符都放入HashSet中,而後遍歷石頭字符串中的每一個字符,到HashSet中查找是否存在,存在的話計數器自增1便可,參見代碼以下:htm

 

解法二:blog

class Solution {
public:
    int numJewelsInStones(string J, string S) {
        int res = 0;
        unordered_set<char> s;
        for (char c : J) s.insert(c);
        for (char c : S) {
            if (s.count(c)) ++res;
        }
        return res;
    }
};

 

參考資料:ip

https://leetcode.com/problems/jewels-and-stones/solution/

https://leetcode.com/problems/jewels-and-stones/discuss/113553/C++JavaPython-Easy-and-Concise-Solution-O(M+N)

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索