1、leetcode409
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 “Aa” 不能当做一个回文字符串
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
d = {}
flag = 0
cnt = 0
for 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 = 1
elif v == 1:
flag = 1
return cnt + flag
2、leetcode290
给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。
class Solution(object):
def wordPattern(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] not in d.keys():
if word[i] not in 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):
def groupAnagrams(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].append(i)
return d.values()
4、leetcode3
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s)==0:
return 0
maxv=1
start=0
d={}
for i in range(len(s)):
if s[i] not in 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):
def findRepeatedDnaSequences(self, s):
"""
:type s: str
:rtype: List[str]
"""
if len(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:
res.append(tmp)
i +=1
res=list(set(res))
return res
6、leetcode76
class Solution(object):
def minWindow(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] not in d:
d[t[i]] =1
else:
d[t[i]] +=1
for i in range(len(s)):
cur[s[i]] = cur.get(s[i],0)+1
if s[i] in d and cur[s[i]]<=d[s[i]]:#若此字符可能是某解
cnt +=1
if cnt == l: #找到一个可能解
while cnt == l: #仍包含可能解
if s[j] in cur:
cur[s[j]]-=1
if s[j] in d and cur[s[j]]<d[s[j]]:
cnt -=1
j +=1
if i-j+2<min_len:
min_len = i-j+2
res = s[j-1:i+1]
return res
好难 哭辽