771.Jewels and Stones

【题目】

You're given stringsJrepresenting the types of stones that are jewels, andSrepresenting the stones you have. Each character inSis a type of stone you have. You want to know how many of the stones you have are also jewels.

The letters inJare guaranteed distinct, and all characters inJandSare letters. Letters are case sensitive, so"a"is considered a different type of stone from"A".

給定字符串J 代表石頭中寶石的類型,和字符串 S代表你擁有的石頭。 S 中每個字符代表了一種你擁有的石頭的類型,你想知道你擁有的石頭中有多少是寶石。

J 中的字母不重複,J 和 S中的所有字符都是字母。字母區分大小寫,因此"a"和"A"是不同類型的石頭。

Example 1:

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

Output:
 3

Example 2:

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

Output:
 0

【思路】

J表示有分數的,S代表你擁有的,就計算即可

【解法】

☆JAVA

簡單的解法,先把答案放到MAP裡面,然後逐項跑題目的迴圈,有對到就+1

class Solution {
    public int numJewelsInStones(String J, String S) {
        int Jint = 0;
        Map map = new HashMap();
        String[] temp = J.trim().split("");
        String[] Stemp = S.trim().split("");
        for(String tempString : temp){
            map.put(tempString, tempString);
        }
        for(int i = 0 ; i < Stemp.length ; i++){
            if(  !Stemp[i].equals("") && map.containsKey(Stemp[i])  ){
                Jint++;
            }
        }
        return Jint;
    }
}

☆Python

跟JAVA一樣 只不過Python可以直再去用字元去比對List (S[i] in JString),所以比較簡單,一樣跑題目迴圈即可

class Solution:
    def numJewelsInStones(self, J, S):
        result = 0;
        JString = list(J);
        for i in range(len(S)):
            if( S[i] in JString):
                result = result +1;

        return result;

results matching ""

    No results matching ""