📣 黑五网一特惠|VIP一年通行证5折,蓝莓、Offer多多同步特惠
12
返回列表 发新帖
楼主: 匿名
跳转到指定楼层
上一主题 下一主题
收起左侧

求 亚麻OA items in containers 的思路

🔗
extreme 2022-8-18 09:04:43 | 只看该作者
全局:
这道题可以用DP O(n)的算法来解决,画了一个图,放在附件里了
用两个数组d1和d2,分别记录从开始到整个字符串里每个字符的*的个数, 和从最后一个位置到之前每个位置的*的个数。“*”的个数可以用下面的公式直接算出来,不用遍历。 num = d1[-1] - d1[start] - d2[end] .
python 的代码如下:
  1. def numberOfItems(s, startIndices, endIndices):
  2.     # Write your code here
  3.     res = []
  4.     d1 = []
  5.     d2 = []
  6.     count = 0
  7.     i = 0

  8.     size = len(s) - 1
  9.     while s[size] == '*':
  10.       size -= 1

  11.     while s[i] == '*':
  12.       i += 1
  13.       d1.append(0)

  14.     while i < size + 1:
  15.       if s[i] == '*':
  16.         count += 1
  17.         d1.append(count)
  18.       elif s[i] == '|':
  19.         d1.append(count)
  20.       i += 1

  21.     d2 = [count - i for i in d1]

  22.     for i in range(len(startIndices)):
  23.         start, end = startIndices[0]-1, endIndices[0]-1
  24.         while s[start] == '*':
  25.           start += 1
  26.         while s[end] == '*':
  27.           end -= 1
  28.         res.append(count - d1[start] - d2[end])
  29.     return res         

  30. s = "*|***|****|*****|**"
  31. startIndices = [1, 1]
  32. endIndices = [10, 11]
  33. print (numberOfItems(s, startIndices, endIndices))
复制代码

本帖子中包含更多资源

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表