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;
    }
    
  • 相关阅读:
    java中Excel导出
    springmvc接收各种参数
    restTemplate使用
    java中io流的操作
    在线Cron表达式生成器
    springBoot实现socketio
    maven的使用
    idea中导入githup项目
    java 单例模式之线程安全的饿汉模式和懒汉模式
    spring定时任务的集中实现
  • 原文地址:https://www.cnblogs.com/neilz/p/10629818.html
Copyright © 2011-2022 走看看