【Lintcode】1038. Jewels And Stones

題目地址:

https://www.lintcode.com/problem/jewels-and-stones/description

給定一個字符串JJ,題目保證JJ中字符兩兩不同;再給定一個字符串SS,問SS中有多少個字符在JJ中出現過,重複次數也要計算。

用哈希表記錄JJ裏有哪些字符,然後遍歷SS並統計即可。代碼如下:

import java.util.HashSet;
import java.util.Set;

public class Solution {
    /**
     * @param J: the types of stones that are jewels
     * @param S: representing the stones you have
     * @return: how many of the stones you have are also jewels
     */
    public int numJewelsInStones(String J, String S) {
        // Write your code here
        Set<Character> set = new HashSet<>();
        for (int i = 0; i < J.length(); i++) {
            set.add(J.charAt(i));
        }
        
        int res = 0;
        for (int i = 0; i < S.length(); i++) {
            if (set.contains(S.charAt(i))) {
                res++;
            }
        }
        
        return res;
    }
}

時空複雜度O(n)O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章