哈希表计数。这道题不会,来自官方题解(. - 力扣(LeetCode))。
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
# 哈希表
chars_cnt = collections.Counter(chars)
ans = 0
for word in words:
word_cnt = collections.Counter(word)
for c in word_cnt:
if chars_cnt.get(c,0) < word_cnt[c]:
# 使用get()避免键不存在
break
else:
ans += len(word)
return ans
模拟+数学
先不看绝对值,ans[i]等于ans[i-1]-nums[i-1]-nums[i]。但是由于带有绝对值,所以使用presum储存起来。而当i==0时,ans[i-1]是presum,而nums[i-1]使用pre(pre初值为0)保存,就方便了当i==0时下标超范围的情况。而presum初值为sum(nums)的原因是,减去pre和nums[0]就为ans[0]。然后在存入数组时,绝对值即可。
class Solution:
def leftRightDifference(self, nums: List[int]) -> List[int]:
# 模拟+数学
pre = 0
presum = sum(nums)
n = len(nums)
ans = [0]*n
for i in range(len(nums)):
presum -= pre + nums[i]
ans[i] = abs(presum)
pre = nums[i]
return ans
无pre:
class Solution:
def leftRightDifference(self, nums: List[int]) -> List[int]:
# 数学
# pre = 0
# presum = sum(nums)
presum = sum(nums)-nums[0]
n = len(nums)
ans = [0]*n
ans[0] = abs(presum)
# for i in range(len(nums)):
for i in range(1,len(nums)):
# presum -= pre + nums[i]
presum -= nums[i-1] + nums[i]
ans[i] = abs(presum)
# pre = nums[i]
return ans
完
感谢你看到这里!一起加油吧!