Merged String Checker Codewars 答题

At a job interview, you are challenged to write an algorithm to check if a given string, s, can be formed from two other strings, part1 and part2.

The restriction is that the characters in part1 and part2 should be in the same order as in s.

The interviewer gives you the following example and tells you to figure out the rest from the given test cases.

For example:

‘codewars’ is a merge from ‘cdw’ and ‘oears’:

s:  c o d e w a r s   = codewars

part1: c d w = cdw
part2: o e a r s = oears

字符串融合,编写一个函数,给定三个参数,s,part1,part2
判断s是不是有part1和part2组合而成的,并且part1和part2的字母顺序应该和S里的字母顺序一致。
函数嵌套可以解决这个问题,但是我第一时间想到的是正则匹配。

import re

def is_merge(s, part1, part2):
    if s == part1 + part2:
        return True
    if len(part1)+len(part2) != len(s) or sorted(list(s)) != sorted(list(part1+part2)):
        return False
    list1 = []
    list2 = []
    for a in part1:
        if a.isalnum():
            list1.append(a)
        else:
            a = '\\' + a
            list1.append(a)
    for b in part2:
        if b.isalnum():
            list2.append(b)
        else:
            b = '\\' + b
            list2.append(b)
    getRegex1 = re.compile('.*'+'.*'.join(list1)+'.*')
    getRegex2 = re.compile('.*'+'.*'.join(list2)+'.*')
    return True if getRegex1.match(s) and getRegex2.match(s) else False

你可能感兴趣的:(Python学习)