Leetcode两道小题目python试水

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上没办法正确运行,有待考察。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值