Leetcode Hash Table专题 389. Find the Difference+771. Jewels and Stones+554. Brick Wall

本文介绍两种字符串操作技巧,一是找出被添加的字符,二是计算共有宝石的数量。通过使用collections.Counter生成字典并进行字典操作来解决这两类问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.
class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        
        ds = collections.Counter(s)
        dt = collections.Counter(t)
        return (dt - ds).keys().pop()
                
 

771Jewels and Stones

 

You're given strings J representing the types of stones that are jewels, and S representing the stones you have.  Each character in Sis 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".

Example 1:

Input: J = "aA", S = "aAAbbbb"
Output: 3

Example 2:

Input: J = "z", S = "ZZ"
Output: 0

Note:

  • S and J will consist of letters and have length at most 50.
  • The characters in J are distinct.

 

class Solution(object):
    def numJewelsInStones(self, J, S):
       """
        :type J: str
        :type S: str
        :rtype: int
        """
        result=0
        
        cntJ=collections.Counter(J)
        cntS=collections.Counter(S)
        total_S_type=len(cntS)
        inter = dict.fromkeys([x for x in cntJ if x in cntS])
        Jkeys= inter.keys()
        for key,value in cntS.items():
            if key in Jkeys:
                result=result+value
        
        return result

 

总结:两道题解题思路相似,都是用collections.Counter生成字典。要熟悉字典相关操作

 

There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the leastbricks.

The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.

If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.

You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.

Example:

Input: 
[[1,2,2,1],
 [3,1,2],
 [1,3,2],
 [2,4],
 [3,1,2],
 [1,3,1,1]]
Output: 2
Explanation: 

 

Note:

  1. The width sum of bricks in different rows are the same and won't exceed INT_MAX.
  2. The number of bricks in each row is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won't exceed 20,000.

class Solution(object):
    def leastBricks(self, wall):
        """
        :type wall: List[List[int]]
        :rtype: int
        """
        spaceMap = dict()
        for row in wall:
            spacelen = 0
            for brick in row[:-1]: # avoid counting wall edge 这样可以造成不算整面墙最右边的墙缝的效果,按题意也不能在最右边的墙缝划线
                spacelen += brick
                if spacelen not in spaceMap:
                    spaceMap[spacelen] = 1
                else:
                    spaceMap[spacelen] += 1
        try:
            least = len(wall) - max(spaceMap.values())
        
        except:#比如输入是[[1],[1],[1]]的时候,就会进到这里,因为spaceMap是空会抛出异常
            least=len(wall)
            
        return least
              
这道题的解法确实是精妙哎!不是我原创的,学习了。比如题目中给的例子,6层的墙,spaceMap如下:

1:3次

2:1次

3:3次

4:4次

5:2次

spaceMap里的key代表从每层最左边开始数的长度(可以理解为恰好是两块砖之间缝的地方)

层数-max(spaceMap.values()) 就能得到最少穿过的砖数

 



        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值