如何使这2个字符串匹配算法更有效?

问题描述

因此,我正在进行有关代码战争的练习,并且我的代码执行了应做的事情,但是它需要提高效率,而且我不知道我还能做什么。下面是我编写的练习和代码

完成函数scramble(str1,str2),如果可以重新排列一部分str1字符以匹配str2,则返回true,否则返回false。

注意:

仅使用小写字母(a-z)。不包含标点符号或数字。 性能需要考虑

Input strings s1 and s2 are null terminated.

示例

scramble('rkqodlw','world') ==> True
scramble('cedewaraaossoqqyt','codewars') ==> True
scramble('katas','steak') ==> False
def scramble(s1,s2):
    #initiate variables
    i,j,count =0,0
   #sorting our 2 strings
    s1,s2="".join(sorted(s1)),"".join(sorted(s2))
    #for loop to go over each character in the str we want to match,s2
    for j in range(len(s2)):
        
        #while loop to go over s1 to match characters to s2 char
        i=0
        while i<len(s1):
            #when 2 chars match,count increases by 1,i increases to exit while loop
            #s1 sliced for increasing efficiency in the next loop
            if s1[i]==s2[j]:
                count+=1
                x=i 
                i=len(s1)
                s1=s1[x+1:]
            
            #if character larger in s1,no need to go through the whole string
            #therefore,exits while loop and slices
            elif s1[i]>s2[j]:
                x=i 
                i=len(s1)
                s1=s1[x+1:]
            
            #increases iterator
            else: i+=1
    
    #return statement,if count equals length of s2 then it must be true
    if len(s2)==count: return True
    else: return False

侧面问题:此代码的时间复杂度为O(n ^ 2)吗?

解决方法

因此,在这里,您要对这两个字符串进行排序,这两个字符串给出 n m 的大小的 O(n log n + m log m)复杂度s1s2中的一个。然后,您将运行两个嵌套循环,以检查s2中的字符是否存在于s1中,如果问题字符确实存在,则重写s1。这实际上是效率极低的,确实给了您 O(nm)那个部分复杂性,并且顶部有一个很大的常数(因为您要一遍又一遍地重写字符串)。

相反,您可以只计算每个字符串中每个字符的出现次数,以查看是否有足够的字符来组成s2中的s1。这将为您提供线性时间以及一个字母的大小,这是一个很小的常数(在您的情况下为26,因为根据询问提示仅允许使用小写字母字符)。

,

如果您尝试从不存在的列表中查找并弹出元素,则可以利用抛出异常的事实:

def scramble(s1,s2):
    l1 = list(s1)
    for c in s2:
        try:
            i = l1.index(c)
            l1.pop(i)
        except:
            return False
    return True