Question
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:
Example 1:
Input: J = "aA", S = "aAAbbbb" Output: 3
Example 2:
Input: J = "z", S = "ZZ" Output: 0
Note:
SandJwill consist of letters and have length at most 50.- The characters in
Jare distinct.
Answer One
class Solution { /** * @param String $J * @param String $S * @return Integer */ function numJewelsInStones($J, $S) { $Js = str_split($J); $sum = 0; foreach($Js as $v) { $sum += substr_count($S, $v); } return $sum; } }

Answer Two
class Solution { /** * @param String $J * @param String $S * @return Integer */ function numJewelsInStones($J, $S) { // $Js = str_split($J); $Ss = str_split($S); $sum = 0; $res = array_count_values($Ss); foreach($res as $k => $v) { if(strpos($J, $k) !== false) { $sum += $v; } } return $sum; } }

PHP 原生函数大法好...
本文介绍了一种使用PHP编程语言解决LeetCode题目的方法,题目要求计算给定字符串中属于宝石类型的石头数量。提供了两种解决方案,一种是通过遍历宝石类型并计算其在石头字符串中出现的次数,另一种是先统计所有石头的频率,再筛选出宝石类型的石头数量。

被折叠的 条评论
为什么被折叠?



