Leetcode 算法题20

345Reverse Vowels of a String

给出一个字符串,将其中元音字母的顺序反过来

Example 1:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

Note:
The vowels does not include the letter "y".

我的代码:

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        ans = list(s)
        vowels = ['a','e','i','o','u','A','E','I','O','U']
        front = 0
        back = len(ans)-1
        while front < back:
            if ans[front] in vowels and ans[back] in vowels:
                ans[front],ans[back] = ans[back],ans[front]
                front += 1
                back -= 1
            elif s[front] in vowels:    #这行以下的代码用if而非elif可以省去最后else的判断
                back -= 1
            elif s[back] in vowels:
                front += 1
            else:
                front += 1
                back -= 1
        return ''.join(ans)
大神的代码:了解re模块中sub替换函数

def reverseVowels(self, s):
    vowels = re.findall('(?i)[aeiou]', s)
    return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s)

#It’s possible in one line, but I don’t really like it:
def reverseVowels(self, s):
    return re.sub('(?i)[aeiou]', lambda m, v=re.findall('(?i)[aeiou]', s): v.pop(), s)

#Another version, finding replacement vowels on the fly instead of collecting all in advance:
def reverseVowels(self, s):
    vowels = (c for c in reversed(s) if c in 'aeiouAEIOU')
    return re.sub('(?i)[aeiou]', lambda m: next(vowels), s)


235 Lowest Common Ancestor of a Binary Search Tree

给出一个树和其中两个节点,求这两个节点的最低同一祖先节点

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

我的代码:第一次接触树学到的标准二叉搜索树的定义

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if root:
            if q.val < root.val > p.val:
                return self.lowestCommonAncestor(root.left,p,q)
            elif q.val > root.val < p.val:
                return self.lowestCommonAncestor(root.right,p,q)
            else:
                return root
大神的代码:

def lowestCommonAncestor(self, root, p, q):
    while (root.val - p.val) * (root.val - q.val) > 0:
        root = (root.left, root.right)[p.val > root.val]
    return root


459 Repeated Substring Pattern
给出一个字符串,判断其是否由其本身一个子字符串重复组成

Example 1:

Input: "abab"

Output: True

Explanation: It's the substring "ab" twice.

Example 2:

Input: "aba"

Output: False

Example 3:

Input: "abcabcabcabc"

Output: True

Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
我的代码:

class Solution(object):
    def repeatedSubstringPattern(self, s):
        """
        :type s: str
        :rtype: bool
        """
        l = len(s)
        for i in range(1,int(math.ceil(l/2))+1):
            if l % i == 0 and s[:i]*(l/i) == s:
                return True
        return False
大神的代码:这个思路很奇妙

def repeatedSubstringPattern(self, str):
    return str in (2 * str)[1:-1]


367 Valid Perfect Square

判断一个数是否刚好为另一个数的平方

我的代码:确定一个范围后用二分法

class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        end = 10 ** ((len(str(num))+1) / 2)
        start = end / 10 -1
        while end-start > 1:
            guess = (start+end) // 2
            square = guess ** 2
            if square > num:
                end = guess
            elif square < num:
                start = guess
            else:
                return True
        return False
大神的代码:这个式子以前的mit课程学过,想到过但是实在太久了记不起细节,是比二分法更快的收敛算法

    r = x
    while r*r > x:
        r = (r + x/r) / 2
    return r*r == x

110 Balanced Binary Tree

判断一个树是够平衡,每个子节点左右深度差不超过1

我的代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        def dfs(node,depth):
            if node:
                depth += 1
                if not (node.left or node.right):
                    return depth
                return max(dfs(node.left,depth),dfs(node.right,depth))
            else:
                return 0
        stack = [root]
        while stack:
            node = stack.pop()
            if abs(dfs(node.left,0) - dfs(node.right,0)) > 1:
                return False
            if node.left:stack.append(node.left)
            if node.right:stack.append(node.right)
        return True
大神的代码:
class Solution(object):
    def isBalanced(self, root):
            
        def check(root):
            if root is None:
                return 0
            left  = check(root.left)
            right = check(root.right)
            if left == -1 or right == -1 or abs(left - right) > 1:
                return -1
            return 1 + max(left, right)
            
        return check(root) != -1

#Iterative, based on postorder traversal:
class Solution(object):
    def isBalanced(self, root):
        stack, node, last, depths = [], root, None, {}
        while stack or node:
            if node:
                stack.append(node)
                node = node.left
            else:
                node = stack[-1]
                if not node.right or last == node.right:
                    node = stack.pop()
                    left, right  = depths.get(node.left, 0), depths.get(node.right, 0)
                    if abs(left - right) > 1: return False
                    depths[node] = 1 + max(left, right)
                    last = node
                    node = None
                else:
                    node = node.right
        return True








345 Reverse Vowels of a String
367 Valid Perfect Square
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值