最前面是所有的總結。
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.
超時了,應該是不能出現的複雜度