Leetcode Exercise 4

Jewels and Stones

Wendy Wu
W-Learning Note
3 min readNov 29, 2018

--

Description

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中每一個字代表你有的石頭,你想知道你有的石頭裡面,有幾個珠寶。

字串J中所有的字都不同,且J和S中都只有字母,大小寫視為不同。

Example

#1
Input: J = "aA", S = "aAAbbbb"
Output: 3
#2
Input: J = "z", S = "ZZ"
Output: 0

構思

  1. 將將J字串的字一個一個比對S有幾個
  2. 將所有數字相加

實作程式碼

# @param {String} j
# @param {String} s
# @return {Integer}
def num_jewels_in_stones(j, s)
ans = 0
j.each_char { |char|
ans += s.count(char)
}
return ans
end

結果

beats 92.72%

Runtime最短的寫法: 44 ms

def num_jewels_in_stones(j, s)     
s.count(j)
end

嗯……看起來其實用一個count就可以解決了,

那就來看看count這個method的用法吧,直接看下面的結果:

count

可以看到,不管用”A”還是”AA”,在”aAAbbbb”中得到的結果都是2,

原因是count計算的是字母(characters),不是字串,所以不管是AA還是A,結果都是一樣的。

那如果我是想算”AA”的數量呢?可以參考這篇stackoverflow

--

--