LeetCode:771Jewels and Stones

problem

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

solution

方法一

思路过程
第一次看错题题意了,( ̄ε(# ̄)
字符串J中的这些字母代表宝石
字符串S中代表你有的石头
求的就是再你有得石头中有多少得宝石
第一个想法就是burte force(暴力搜索),直接把S中所有都遍历一次,看是不是J中有的
这里,不知道python和Java提供的字符串操作背后的效率是怎样的(见下面的知识总结)如果是线性的,建议改为python的集合或则java的hash

知识总结
What’s a faster operation, re.match/search or str.find?

这个问题链接说明了python中查找中in相对于find和match是最快的
并且 in的查找效率是依据后面可迭代的数据而定的

代码

python

class Solution:
    def numJewelsInStones(self, J: str, S: str) -> int:
        count=0
        for i in S:
            if i in J:
                count+=1
        return count

Java

class Solution {
    public int numJewelsInStones(String J, String S) {
        int count = 0;
        for (int i = 0; i < S.length(); ++i) {
            if (J.indexOf(S.charAt(i)) != -1) {
                count++;
            }
        }
        return count;
    }
}
方法二

思路
变成hash查找,在效率上会提升

代码

python

class Solution:
    def numJewelsInStones(self, J: str, S: str) -> int:
        J=set(J)
        count=0
        for i in S:
            if i in J:
                count+=1
        return count

Java

class Solution {
    public int numJewelsInStones(String J, String S) {
        int count = 0;
        Set<Character> hashset = new HashSet<>();
        for (char c : J.toCharArray()) {
            hashset.add(c);
        }
        for (char c : S.toCharArray()) {
            if (hashset.contains(c)) {
                ++count;
            }
        }
        return count;
    }
}
方法三

思路
就是用背后的库,遍历J中每一个字符,再S中查找并计数

代码

python

class Solution:
    def numJewelsInStones(self, J: str, S: str) -> int:
        count=0
        for i in J:
            count+=S.count(i)
        return count

后续想法

  • 其实,更加深层一点就是可以比较两个字符串的长度,如果查找更快,用多的字符串查找,少的字符串遍历,只是猜测

  • 当然还可以试试先把S优化,把没用的重复的先给去除掉,这个我暂时没想出什么好的点子,如果看到的读者有方法的话,可以留言交流呀 谢啦!!☆⌒(*^-゜)v

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值