美团 8/29 笔试题 算法第三题解法(python)

import sys
from collections import defaultdict
from bisect import bisect_left

s = sys.stdin.readline().strip()
a = sys.stdin.readline().strip()


def getIdx(s, a):
    ch2indices = defaultdict(list)
    for i, ch in enumerate(s):
        ch2indices[ch].append(i)

    for ch in a:
        if ch not in ch2indices:
            return -1

    indices = []
    continue_seq = ''
    ith = 0
    sidx = 0
    while ith < len(a):
        ch = a[ith]
        idx = bisect_left(ch2indices[ch], sidx)
        if idx != len(ch2indices[ch]):
            continue_seq += ch
            sidx = ch2indices[ch][idx] + 1
            ith += 1
        else:
            indices.append(sidx)
            continue_seq = ''
            sidx = 0

    if continue_seq:
        indices.append(sidx)
    total_idx = len(s) * (len(indices) - 1) + indices[-1] - len(a)
    return total_idx


print(getIdx(s, a))


#美团笔试##美团##笔经#
全部评论

相关推荐

见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
07-07 12:25
门头沟学院 Java
程序员牛肉:你这个智邮公司做的就是那个乐山市税务系统的服务吗?
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务