美文网首页
LeetCode: 771. Jewels and Stones

LeetCode: 771. Jewels and Stones

作者: sasky2008 | 来源:发表于2019-02-14 16:24 被阅读1次

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


    理解一下:
    J和S都是字符串(char数组).
    S中包含多少个J所包含的单个字符(char)
    需要区分大小写


      例子:
      Input: J = "aA", S = "aAAbbbb"
      Output: 3
    
      例子:
      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最大长度为50. J.length <= 50

    我的答案

    class Solution {
        func numJewelsInStones(_ J: String, _ S: String) -> Int {
            var count = 0
            var j_dic = [Character: Int]()
            for (offset , element) in J.enumerated() {
                j_dic[element] = offset
            }
            for (_, element) in S.enumerated() {
                if let _ = j_dic[element] {
                    count += 1
                }
            }
            return count
        }
    }
    

    Leetcode出处网址

    如果有更好的解法, 欢迎留言

    相关文章

      网友评论

          本文标题:LeetCode: 771. Jewels and Stones

          本文链接:https://www.haomeiwen.com/subject/kygeeqtx.html