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上沒辦法正確運行,有待考察。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章