博客
关于我
poj1936 假期计划第一水
阅读量:802 次
发布时间:2023-03-03

本文共 1281 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要判断一个字符串 s 是否是另一个字符串 t 的子序列。子序列的定义是可以通过删除 t 中的某些字符,使得剩下的字符顺序与 s 完全一致。

方法思路

为了高效地解决这个问题,我们可以使用预处理和二分查找的方法。具体步骤如下:

  • 预处理 t: 创建一个字典,其中每个字符映射到它在 t 中出现的所有索引列表。这样我们可以快速查找特定字符的位置。
  • 遍历 s: 对于 s 中的每个字符,使用二分查找在对应的索引列表中找到下一个出现位置。如果找到,则更新当前位置,否则返回 false。
  • 终止条件: 如果遍历完所有字符且顺序正确,返回 true。
  • 这种方法的时间复杂度为 O(len(t) + len(s) * log len(t)),能够高效处理较大规模的输入。

    解决代码

    import sysfrom bisect import bisect_leftfrom collections import defaultdictdef is_subsequence(s, t):    if not s:        return True    pos_map = defaultdict(list)    for idx, c in enumerate(t):        pos_map[c].append(idx)    j = 0    for c in s:        if c not in pos_map:            return False        lst = pos_map[c]        pos = bisect_left(lst, j)        if pos >= len(lst):            return False        j = pos + 1    return Truedef main():    input = sys.stdin.read().split()    n = len(input)    for i in range(0, n, 2):        s = input[i]        t = input[i+1]        if is_subsequence(s, t):            print("Yes")        else:            print("No")if __name__ == "__main__":    main()

    代码解释

  • 预处理 t: 使用 defaultdict 创建一个字典 pos_map,其中每个字符映射到它在 t 中的所有索引位置。
  • 遍历 s: 对于每个字符 c,使用二分查找找到在 t 中大于当前位置 j 的下一个索引。如果没有找到,返回 false。
  • 更新位置: 找到下一个索引后,更新 j 到该索引的下一个位置,继续遍历下一个字符。
  • 处理输入: 读取所有输入,逐对处理每个测试用例,输出结果。
  • 这种方法确保了在处理大规模输入时的高效性,正确性也得到了保证。

    转载地址:http://bdxfk.baihongyu.com/

    你可能感兴趣的文章
    python anaconda 安装使用
    查看>>
    python and或or 当参数传递的时候的用法
    查看>>
    Python append() 与列表上的 + 运算符,为什么这些会给出不同的结果?
    查看>>
    Python APP自动化测试工具adb与Monkey使用详解
    查看>>
    Python APP自动化测试框架Appium详解
    查看>>
    Python APP自动化测试框架开发实战
    查看>>
    python argparse模块
    查看>>
    Python asyncio库的学习和使用
    查看>>
    Python AttributeError:“dict“对象没有属性“append“
    查看>>
    Python base64和hashlib模块
    查看>>
    python basic programs
    查看>>
    python bert_gen.py 报错Unable to load weights from pytorch checkpoint file for......
    查看>>
    python binascii.Error: Incorrect padding
    查看>>
    Python bool() 函数能否为无效参数引发异常?
    查看>>
    Python C 程序子进程在“for line in iter“处挂起
    查看>>
    Python Celery:自动化测试平台定时任务必备的三方库
    查看>>
    python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令
    查看>>
    Python CONNECT 4 CHECK WIN函数
    查看>>
    python cos,Python cos(90)和cos(270)不是0
    查看>>
    python进阶(4):Python 脚本文件重启自身进程
    查看>>