前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >06 Jewels and Stones

06 Jewels and Stones

作者头像
devi
发布2021-08-18 15:50:54
2480
发布2021-08-18 15:50:54
举报
文章被收录于专栏:搬砖记录

题目

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:

代码语言:javascript
复制
S and J will consist of letters and have length at most 50.
The characters in J are distinct.

分析

题意:给出一串字符串J表示宝石,一串S表示你拥有的石头,从S中查看你拥有多少个宝石,大小写敏感。

最暴力的解法就是两层循环,将J中的字符与S中的字符一一比对。

代码语言:javascript
复制
class Solution {
    public int numJewelsInStones(String J, String S) {
        int sum=0;
        for(char j:J.toCharArray()){
            for(char s:S.toCharArray()){
                if(j==s)
                    sum++;
            }
        }
        return sum;
    }
}

java字符串不能直接遍历,需要转成字符数组

但是显然这种方法是不可取的,成本太高。

在这里插入图片描述
在这里插入图片描述

没想到其他方法,看了下评论区

最装逼的一行java代码

在这里插入图片描述
在这里插入图片描述

利用正则表达式的特性,但是速度太慢了,空间复杂度也不见得减小。

代码语言:javascript
复制
return S.replaceAll("[^" + J + "]", "").length();

降低时间复杂度

如果数据够大,下面这个算法能够明显降低耗时。

思路:

  • 将宝石放入集合(无序、互异、确定)中;
  • 如果宝石集合包含S中的石头,则计数加一

关键就在于将宝石J放在了一个具有“对外分辨”能力的盒子里。

代码语言:javascript
复制
class Solution {
    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;
    }
}

最快的方法

在这里插入图片描述
在这里插入图片描述
代码语言:javascript
复制
class Solution {
    public int numJewelsInStones(String J, String S) {
       int res=0;
       for(char c : S.toCharArray()){
           if(J.indexOf(c) != -1){
               res++;
           }
       }
       return res;
    }
}

思路一样:遍历石头,如果存在宝石,则计数加一。

这道算法题更多的是考察工具的使用,解题思想基本一致。

扩展

如果本题改为大数据题,假设石头S的个数是以亿为单位,从中找出宝石的个数,可以采取以下思路。

  • 将石头S映射到int[] stones[52]中,stones中的数据表示该下标的对应字母拥有个数(下标映射集合a~z,A~Z,分别对应到0~25,26~51。)。 如:stones[2]=300,表示字母“c”的个数有300个。
  • 将宝石J映射到int[] jewels[52]中,jewels[n]=1表示对应的字母为宝石
  • sum(stones[jewels[i]]),其中 i∈[0,25],jewels[i]=1

时间复杂度O(n);

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/01/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 分析
    • 最装逼的一行java代码
      • 降低时间复杂度
        • 最快的方法
        • 扩展
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档