更新…
2 . Add Two Numbers
#python2
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l3 = ListNode(0) #新建一个节点
tem = l3 #表头
l3sum = 0
if l1 is None:
return l2
if l2 is None:
return l1
while True:
if l1 != None:
l3sum = l3sum + l1.val
l1 = l1.next
if l2 != None:
l3sum = l3sum + l2.val
l2 = l2.next
tem.val = l3sum % 10
l3sum = int(l3sum/10)
if l1 == None and l2 == None and l3sum == 0:
break
tem.next = ListNode(0)
tem = tem.next
return l3
12 . Integer to Roman. Integer to Roman
分析: 将数字每一位分割,分别对每一位数字进行转化
class Solution(object): #python
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
dict = {0:("","I","II","III","IV","V","VI","VII","VIII","IX"),
1:("","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"),
2:("","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"),
3:("","M","MM","MMM")}
sr = []
sr.append(dict[3][num/1000%10])
sr.append(dict[2][num/100%10])
sr.append(dict[1][num/10%10])
sr.append(dict[0][num%10])
s=''
for i in sr:
s=s+i
return s
python3 运行报错
13. Roman to Integer
题目出处:LeetCode
分析: 从题目中可以发现罗马数字有其一一对应的数值,所以想到使用Python中的字典。
class Solution: #python3
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
sum = 0
dict = {'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1}
for i in range(len(s)-1):
if dict[s[i]] < dict[s[i+1]]:
sum-=dict[s[i]]
else:
sum+=dict[s[i]]
sum+=dict[s[-1]] #加上最后一位
return sum
20.Valid Parentheses
此题判断括号是否匹配,采用栈结构
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for ch in s:
if ch == '(' or ch == '[' or ch == '{' :
stack.append(ch)
else:
if not stack:
return False
if ch == ')' and stack[-1]!= '(' or ch == ']' and stack[-1]!='[' or ch == '}' and stack[-1]!='{':
return False
stack.pop()
return not stack