题目
思路
这道题就是看货架上能满足多少客户需求。不用考虑顺序问题。首先使用字典(need_dict)记录每种商品的需求数,再遍历货架商品,查询是否在字典(need_dict)中有剩余需求量,有的话 ans + 1,最后返回 ans。
代码
def solution(n: int, m: int, s: str, c: str) -> int:
# write code here
need_dict = {}
for item in c:
# if need_dict.get(item) is not None:
if item in need_dict:
need_dict[item] += 1
else:
need_dict[item] = 1
ans = 0
for g in s:
# if need_dict.get(g) is not None and need_dict.get(g) > 0:
if g in need_dict and need_dict.get(g) > 0:
need_dict[g] -= 1
ans += 1
return ans
if __name__ == '__main__':
print(solution(3, 4, "abc", "abcd") == 3)
print(solution(4, 2, "abbc", "bb") == 2)
print(solution(5, 4, "bcdea", "abcd") == 4)
复杂度
- 时间复杂度
- 空间复杂度
学到了
python中判断key是否在字典dictName中存在,可以使用:
dictName.get(key) is not None,
也可以:
key in dictName
但是直接dictName[key]在健不存在时会报keyError异常