zoukankan      html  css  js  c++  java
  • 771. Jewels and Stones

    771. Jewels and Stones

    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 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.

    时间复杂度 O(mn)

    题目已表示 J 中字母不会重复,就不用考虑循环对比重复计数的问题。所以一开始就想到时间复杂度 O(mn)。字符串字符和字符循环遍历比较。

    public int numJewelsInStones(String J, String S) {
        int num = 0;
        for (int i = 0; i < J.length(); i++) {
            for (int j = 0; j < S.length(); j++) {
                if (J.charAt(i) == S.charAt(j)) {
                    num++;
                }
            }
        }
        return num;
    }
    

    上面方法有点傻的地方,比如 J 的第 1 位字母和 S 第 1 位字母相同,按理说 S 第 1 位字母就没有再比较的必要了。但是上面的方法是每个都比较一遍。

    时间复杂度 O(m+n)

    Explanation

    1. read J and build jewels hash set.
    2. read S and count jewels.

    Time complexity
    I used hash set and it's O(1) to check if it contains an element.
    So the total time complexity will be O(M+N), instead of O(MN)

    public int numJewelsInStones(String J, String S) {
        int res = 0;
        Set setJ = new HashSet();
        for (char j: J.toCharArray()) setJ.add(j);
        for (char s: S.toCharArray()) if (setJ.contains(s)) res++;
        return res;
    }
    
  • 相关阅读:
    SDUTOJ 2775 小P的故事——奇妙的饭卡
    STL vector的构造函数和析构函数(2)
    Spark调研笔记第6篇
    【精】iOS GCD 具体解释
    爆头
    uva 624 CD
    一站式学习Wireshark(转载)
    TCP的状态 (SYN, FIN, ACK, PSH, RST, URG)
    loadrunner两个函数:取参数长度和时间戳函数
    自行控制loadrunner的socket协议性能测试 (转)
  • 原文地址:https://www.cnblogs.com/neilz/p/10629818.html
Copyright © 2011-2022 走看看