leetcode记录(1)771、112

leetcode记录(1)771、112

771 Jewels and Stones

Difficulty: Easy
Acceptance: 82.7%

问题

You’re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.

The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so “a” is considered a different type of stone from “A”.

实现

  1. 两个for循环穷举比较
  2. 用J建立映射表,S取值
class Solution:
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        counter = 0
        for j in J:
            for s in S:
                if j == s:
                    counter += 1
        return counter
class Solution(object):
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        map = [0] * 52
        for j in J:
            if ord(j) >= ord('a') and ord(j) <= ord('z'):
                map[ord(j) - ord('a')] = 1
            else:
                map[ord(j) - ord('A') + 26] = 1
        count = 0
        for s in S:
            if ord(s) >= ord('a') and ord(s) <= ord('z'):
                count += map[ord(s) - ord('a')]
            else:
                count += map[ord(s) - ord('A') + 26]
        return count

结果

254 / 254 test cases passed.
1. Runtime: 43ms. 51.07%
2. Runtime: 41ms. 71.00%

讨论区

单行实现
def numJewelsInStones(self, J, S):
    return sum(map(J.count, S))

39ms. 91.79%

def numJewelsInStones(self, J, S):
    return sum(s in J for s in S)

40ms. 84.58%

利用set

def numJewelsInStones(self, J, S):
        setJ = set(J)
        return sum(s in setJ for s in S)

40ms. 84.58%

112 Path Sum

Difficulty: Easy
Acceptance: 34.7%

问题

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

实现

递归向下,每个节点对sum是否存在路径为左右两个子树对sum-当前节点值是否存在路径的或。

# 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 hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if root == None:
            return False
        elif root.left == None and root.right == None:
            return (sum == root.val)
        else:
            return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)

结果

114 / 114 test cases passed.
Runtime: 59ms. 88.87%

讨论区

基本都是类似的递归方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值