【每日一题0818】乱序匹配

:woman_mage:给定2个由英文小写字母组成的字符串s1s2 ,请编写一个python 函数,当s1 重新组合后能跟s2 相匹配则返回True ,否则返回False

示例:
输入:'saetvhwologr', 'hogwarts' ,输出:True ,因为前者可以重组成lovehogwarts

题目难度:中等
题目来源:codewars

def scramble(s1:str, s2:str):
    pass
  
assert scramble('saetvhwologr', 'hogwarts') is True
assert scramble('rkqodlw', 'world') is True
assert scramble('katas', 'steak') is False
def scramble(s1: str, s2: str):
    s1 = list(s1)
    s2 = list(s2)
    s1_dict = Counter(s1)
    s2_dict = Counter(s2)

    for i in s2:
        if i not in s1:
            return False
        if s2_dict[i] > s1_dict[i]:
            return False
    return True

我也想过,但是这种解法会有bug,比如:
assert scramble('rkqodlw','wood') is False就会断言失败

def scramble(s1: str, s2: str):
    i = 0
    temp = list(s1)
    while i < len(s2):
        if s2[i] in temp:
            index = temp.index(s2[i])
            temp.pop(index)
            i += 1
        else:
            return False
    return True
def scramble(s1: str, s2: str):
    l1 = list(s1)
    l2 = list(s2)
    for i in l1:
        if i in l2:
            l2.remove(i)
    return l2 == []


assert scramble('saetvhwologr', 'hogwarts') is True
assert scramble('rkqodlw', 'world') is True
assert scramble('katas', 'steak') is False
assert scramble('rkqodlw', 'wood') is False

def scramble(s1: str, s2: str):
    list_s1: list = list(s1)
    for c in s2:
        if c in list_s1:
            list_s1.remove(c)
        else:
            return False
    return True

image

from collections import Counter

def scramble(s1: str, s2: str):
    a1 = Counter(s1)
    a2 = Counter(s2)
    return False if [False if a2[i] > a1[i] else False for i in a2 if i not in a1] else True

assert scramble('saetvhwologr', 'hogwarts') is True
assert scramble('rkqodlw', 'world') is True
assert scramble('katas', 'steak') is False
1 个赞

def scramble(s1: str, s2: str):
    list_s1 = list(s1)
    for x in s2:
        try:
            list_s1.pop(list_s1.index(x))
        except:
            return False
    return True


assert scramble('saetvhwologr', 'hogwarts') is True
assert scramble('rkqodlw', 'world') is True
assert scramble('katas', 'steak') is False
assert scramble('rkqodlw', 'wood') is False
def scramble(s1: str, s2: str):
    for s in set(s2):
        if s not in s1 or s1.count(s) < s2.count(s):
            return False
    return True


assert scramble('saetvhwologr', 'hogwarts') is True
assert scramble('rkqodlw', 'world') is True
assert scramble('katas', 'steak') is False
assert scramble('rkqodlw','wood') is False
def scramble(s1: str, s2: str):
    s=0
    s1_list=[a for a in s1]
    for i in range(len(s2)):
        if s2[i] in s1_list:
            s1_list.pop(s1_list.index(s2[i]))
            s+=1
            continue
    if s == len(s2):
        return True
    else:
        return False


assert scramble('saetvhwologr', 'hogwarts') is True
assert scramble('rkqodlw', 'world') is True
assert scramble('katas', 'steak') is False