1、leetcode409
給定乙個包含大寫字母和小寫字母的字串,找到通過這些字母構造成的最長的回文串。
在構造過程中,請注意區分大小寫。比如 「aa」 不能當做乙個回文字串
class
solution
(object):
deflongestpalindrome
(self, s)
:"""
:type s: str
:rtype: int
"""d =
flag =
0 cnt =
0for i in s:
if i in d:
d[i]+=1
else
: d[i]=1
for i in d.keys():
v = d.get(i)
if v%2==
0:cnt += v
elif v>1:
cnt += v-
1 flag =
1elif v ==1:
flag =
1return cnt + flag
2、leetcode290
給定一種規律 pattern 和乙個字串 str ,判斷 str 是否遵循相同的規律。
class
solution
(object):
defwordpattern
(self, pattern,
str)
:"""
:type pattern: str
:type str: str
:rtype: bool
"""l =
len(pattern)
word =
str.split(
)if l !=
len(word)
:return
false
d =for i in
range
(l):
if pattern[i]
notin d.keys():
if word[i]
notin d.values():
#這裡注意是乙個雙向dict,因此要判斷value值也是唯一的
d[pattern[i]
]=word[i]
else
:return
false
else
:if d[pattern[i]
]!= word[i]
:return
false
return
true
3、leetcode49
class
solution
(object):
defgroupanagrams
(self, strs)
:"""
:type strs: list[str]
:rtype: list[list[str]]
"""d =
res=
for i in strs:
tmp =
str(
sorted
(i))
if tmp not
in d:
d[tmp]
=[i]
else
: d[tmp]
return d.values(
)
4、leetcode3
class
solution
(object):
deflengthoflongestsubstring
(self, s)
:"""
:type s: str
:rtype: int
"""iflen
(s)==0:
return
0 maxv=
1 start=
0 d=
for i in
range
(len
(s))
:if s[i]
notin d:
d[s[i]]=i
else
: maxv=
max(maxv,i-start)
start =
max(d[s[i]]+
1,start)
#更新start這一步很重要,要保證start是當前max start
d[s[i]]=i
maxv =
max(maxv,i-start+1)
return maxv
5、leetcode187
class
solution
(object):
deffindrepeateddnasequences
(self, s)
:"""
:type s: str
:rtype: list[str]
"""iflen
(s)<10:
return
d=i=
0 res=
while i+
9<
len(s)
: tmp =
str(s[i:i+10]
)if tmp not
in d:
d[tmp]=1
else
: i +=
1 res=
list
(set
(res)
)return res
6、leetcode76
class
solution
(object):
defminwindow
(self, s, t)
:"""
:type s: str
:type t: str
:rtype: str
"""d=
cur =
#記錄當前字串字元個數
l =len(t)
j=0 cnt=
0 res =
"" min_len =
float
('inf'
)for i in
range
(l):
if t[i]
notin d:
d[t[i]]=
1else
: d[t[i]]+=
1for i in
range
(len
(s))
: cur[s[i]
]= cur.get(s[i],0
)+1if s[i]
in d and cur[s[i]
]<=d[s[i]]:
#若此字元可能是某解
cnt +=
1if cnt == l:
#找到乙個可能解
while cnt == l:
#仍包含可能解
if s[j]
in cur:
cur[s[j]]-=
1if s[j]
in d and cur[s[j]
]cnt -=
1 j +=
1if i-j+
2min_len = i-j+
2 res = s[j-
1:i+1]
return res
好難 哭遼 2020 7 12雜湊 滑動視窗
輸入字串s和t,求出t中由和s相同字母構成序列的數目 可包括s 輸入abc abcbac 輸出3 abc cba bac include include include include include includeusing namespace std typedef long long ll c...
滑動視窗leetcode
給定乙個陣列 nums,有乙個大小為 k 的滑動視窗從陣列的最左側移動到陣列的最右側。你只可以看到在滑動視窗 k 內的數字。滑動視窗每次只向右移動一位。返回滑動視窗最大值。示例 輸入 nums 1,3,1,3,5,3,6,7 和 k 3輸出 3,3,5,5,6,7 解釋 滑動視窗的位置 最大值 1 ...
leetcode 滑動視窗
面試題57 ii.和為s的連續正數序列 題目 輸入乙個正整數 target 輸出所有和為 target 的連續正整數序列 至少含有兩個數 序列內的數字由小到大排列,不同序列按照首個數字從小到大排列。題解 摘自 什麼是滑動視窗 滑動視窗可以看成陣列中框起來的乙個部分。在一些陣列類題目中,我們可以用滑動...