01 | Jewels and Stones

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:

  • S and J will consist of letters and have length at most 50.
  • The characters in J are 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;
    }
}

Native PHP functions that Dafa is good! ...

 

Guess you like

Origin www.cnblogs.com/hututu77/p/10964506.html