20、有效的括号
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
dict = {
')': '(',
']': '[',
'}': '{'
}
print(dict)
lst=[]
for item in s:
if item in '([{':
lst.append(item)
else:
if (len(lst) ==0 ) or lst[-1]!=dict[item]:
return False
lst.pop()
if (len(lst)==0):
return True
else:
return False
21、合并两个有序链表
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def mergeTwoLists(self, list1, list2):
"""
合并两个有序链表为一个升序排列的新链表
:type list1: Optional[ListNode]
:param list1: 第一个链表的头节点
:type list2: Optional[ListNode]
:param list2: 第二个链表的头节点
:rtype: Optional[ListNode]
:return: 合并后新链表的头节点
"""
current = list1
lst=[]
while current is not None:
lst.append(current.val)
current = current.next
current = list2
while current is not None:
lst.append(current.val)
current = current.next
if not lst:
return None
lst.sort()
dummy=ListNode(lst[0])
rlst=dummy
for i in range(1,len(lst)):
rlst.next=ListNode(lst[i])
rlst=rlst.next
return dummy
105、同构字符串
class Solution(object):
def isIsomorphic(self, s, t):
"""
判断两个字符串是否同构(字符映射关系一致)
参数说明:
:type s: str -- 输入的第一个字符串
:type t: str -- 输入的第二个字符串
:rtype: bool -- 返回是否满足同构关系
实现逻辑:
1. 双向验证字符映射关系
2. 建立s到t的字符映射表,验证每个s字符对应唯一的t字符
3. 建立t到s的字符映射表,验证每个t字符对应唯一的s字符
"""
if len(s)!=len(t):
return False
lst1 = ''
lst2 = ''
for i in range(len(s)):
if s[i] not in lst1:
lst1 += s[i]
lst2 += t[i]
else:
if lst2[lst1.index(s[i])] != t[i]:
return False
lst3 = ''
lst4 = ''
for i in range(len(t)):
if t[i] not in lst3:
lst3 += t[i]
lst4 += s[i]
else:
if lst4[lst3.index(t[i])] != s[i]:
return False
return True
def isIsomorphic1(self, s, t):
"""
判断两个字符串是否同构。
两个字符串同构的条件是:s中的每个字符都可以被唯一替换为t中的对应字符,
且不同字符不能映射到同一个字符(双射关系)。
参数:
s (str): 第一个待验证的字符串
t (str): 第二个待验证的字符串
返回值:
bool: 满足同构关系返回True,否则返回False
"""
l=len(s)
l_1=len(t)
if l_1!=l:
return False
dic={}
for i in range(l):
if s[i] not in dic:
if t[i] in dic.values():
return False
dic[s[i]]=t[i]
if dic[s[i]]!=t[i]:
return False
return True