每日leetcode(9.19-9.23)

最前面是所有的总结。
from collections import Counter
判断一个字符是否在另一个字符串中可使用 in
list中也可以使用,判断一个“东西”是否是ta的成员
集合的运算在集合间进行其中 & 求交集 | 求并集 - 求差集 ^ 求对称差

771. Jewels and Stones(Easy)

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

class Solution:
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        from collections import Counter
        dict_s = Counter(S)
        dict_j = set(J)
        count_j = 0
        for type_s in dict_s:
            if set(type_s)&dict_j:
                count_j += dict_s[type_s]
        return count_j

起名无能请忽视恶心的变量名。

一个问题在leetcode 中 print 函数输出要求的值会显示为null,应该是leetcode的判别方式是根据return的东西,而不是print出来了什么东西。要注意把输出放在return中。

在这里其实可以使用 list() 的方式把字符串转换为列表,然后就是双重for循环啦。引用 Counter 这个类别主要是在看一些教学视频的时候看到了,想要复习一下,同时复习集合的交并操作。果不其然,模块名字记错了,类名也记错了,在最后加法那里也记错了,集合的交并也记错了。

集合的运算:
1.集合间进行
2.
& 求交集
| 求并集
-求差集
^ 求对称差

Counter类的使用方式
from collections import Counter #不要再记错了

下面是一个更简单的代码

J = set(J)
        return len([s for s in S if s in J])

以及更简单

return len([elem for elem in S if elem in J])

判断一个字符是否在另一个字符串中可使用 in

7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

符号位不变,其他逆序
其实这道题如果用python写的话就变味了,可是C++不熟悉且目前助攻python所以还是使用python来练习。

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x > 2**31-1 or x<-2**31: 
            return 0
        sign = 1 if x > 0 else -1
        x = x if x > 0 else -x
        x_rev = 0
        
        while x:
            x_rev = x_rev * 10 + x % 10
            x //= 10
        
        x = sign*x_rev
        
        if x > 2**31-1 or x<-2**31: 
            return 0
       
        return sign*x_rev

这里有一个坑,转换前后都要是32位的带符号的数字。微笑。

简单的代码

def reverse(self, x):
        x = -int(str(-x)[::-1]) if x < 0 else int(str(x)[::-1])
        return 0 if x < -2147483648 or x > 2147483647 else x

数字的逆序的话,在python里数字和字符串之间可转化,而字符串也有 自带的逆序操作 或者 切片且步长为1。

3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.


超时了,应该是不能出现 O ( n 2 ) O(n^2) O(n2)的复杂度

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值