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

【LeetCode题解---771】Jewels and Stones

作者头像
周三不加班
发布2019-09-04 09:55:29
4430
发布2019-09-04 09:55:29
举报
文章被收录于专栏:程序猿杂货铺程序猿杂货铺

1

题目

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:

代码语言:javascript
复制
Input: J = "aA", S = "aAAbbbb"Output: 3

Example 2:

代码语言:javascript
复制
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.

2

词汇学习

representing 代表 jewels 珠宝 stones 石头 guaranteed 保证

3

惊人而又蹩脚的中文翻译

大概意思是: 给定字符串J和S,求S中在J中出现的字符总数。 注意,区分大小写即a和A不一样。

4

代码实现

01

解法一

* 使用Hash方法

* 通过遍历字符串S和J,两两进行比较,判断stone中有多少颗jewel。

* 时间复杂度为O(s * j)。(s为字符串S的长度,j为字符串J的长度)。

* 空间复杂度为O(1)。

代码如下:

代码语言:javascript
复制
public static int countsJewelsAndStones(String jewels,String stones){
    int count = 0;
    // 判断边界条件
    if (stones == null || jewels == null) {
        return 0;
    }
    Set set = new HashSet<>();
    // 字符串转数组 利用toCharArray方法转换
    char[] arrayJewels = jewels.toCharArray();
    char[] arrayStones = stones.toCharArray();
    // 把S字符串按字节放到set集合中
    for (char temp : arrayJewels) {
        set.add(temp);
    }
    // 判断具体出现次数
    for (char temp : arrayStones) {
        if (set.contains(temp)) {
            count ++;
        }
    }
    return count;
}

02

解法二

* 暴力解法

* 时间复杂度:O(n^2)

* 空间复杂度:O(1)

代码如下:

代码语言:javascript
复制
public static int countsJewelsInStones2(String jewels,String stones) {
    int result = 0;
    char[] arrayJewels = jewels.toCharArray();
    char[] arrayStones = stones.toCharArray();
    for(int i = 0 ; i < arrayJewels.length ; i++) {
        for(int j = 0 ; j < arrayStones.length ; j++) {
            if(arrayJewels[i] == arrayStones[j]) {
                result++;
            }
        }
    }
    return result;
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-09-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员啊粥 微信公众号,前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档