您的位置:首页 > 编程语言 > Python开发

Leetcode两道小题目python试水

2017-04-26 20:27 423 查看
1 . Complex Number Multiply

题目描述:

Given two strings representing two complex numbers.

You need to return a string representing their multiplication. Note i2 = -1 according to the definition.

Example 1:

Input: “1+1i”, “1+1i”

Output: “0+2i”

Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.

Example 2:

Input: “1+-1i”, “1+-1i”

Output: “0+-2i”

Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.

翻译:

接受两个字符串表示的复数,需要返回一个字符串表示的复数,为二者的乘积。

思路:

使用正则表达式匹配出数字,转型之后作乘积再转回。

import re
class Solution(object):
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
cplx_pattern = re.compile(r'(\-?\d*)\+(\-?\d*)i')
m1 = cplx_pattern.search(a)
m2 = cplx_pattern.search(b)
a1 = int(m1.group(1))
a2 = int(m1.group(2))
b1 = int(m2.group(1))
b2 = int(m2.group(2))
c1 = a1*b1-a2*b2
c2 = a2*b1+a1*b2
return str(c1)+'+'+str(c2)+'i'




运行效率并不高,原因是正则表达式匹配较慢,应该用split简单拆分字符串即可。

2 . Construct Binary Tree from Inorder and Postorder Traversal

题目:Given inorder and postorder traversal of a tree, construct the binary tree.

翻译:接收一个树的中序和先序遍历,构造一颗二叉树

思路:根据先序输入将中序输入的列表划分并递归构造

class Treenode(object):
def __init__(self,x):
self.left = None
self.right = None
self.x = x
def view(self):
if(self.left):
self.left.view()
if(self.right):
self.right.view()
print self.x

def getindex(ls,item):
n = 0
for i in ls:
if(i==item):
return int(n)
n = n+1
return -1;

def subBuild(left,right,cur,postorder,tree):
if(postorder and postorder[0] in left):
i = postorder[0]
pos = getindex(left,i)
postorder.pop(0)
tree.left = Treenode(i)
subBuild(left[0:pos],left[pos+1:],i,postorder,tree.left)
if(postorder and postorder[0] in right):
i = postorder[0]
pos = getindex(right,i)
postorder.pop(0)
tree.right = Treenode(i)
subBuild(right[0:pos],right[pos+1:],i,postorder,tree.right)
return tree

def buildTree(inorder, postorder):
if(inorder):
i = postorder[0]
pos = getindex(inorder,i)
postorder.pop(0)
t = Treenode(i)
return subBuild(inorder[0:pos],inorder[pos+1:],i,postorder,t)


不知道为什么编译测试无误,但在Leetcode上没办法正确运行,有待考察。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python