有没有更快的方法使这段代码更快?

is there a faster way to make this code faster?

所以我们的任务是让下面的代码更快,因为有一些代码示例需要输入非常大的字符串,任何帮助都可以。


w = input()
e = input()

aasd = ''
i = 0

for i in range(len(w)):
    elif e[i] in w:
        aasd = aasd + 'b'
    i = i + 1

print(aasd)

这里最昂贵的操作似乎是 elif b[i] in a(具有复杂性 O(len(a)),因为字符串查找没有像集合那样优化。您可以在 a 中创建一组字符以使查找更快。

import sys

z = int(input())
a = input()
set_a = set(a)
b = input()

strs = ''

for i in range(z):
    if b[i] == a[i]:
        strs = strs + 'a'
    elif b[i] in set_a:
        strs = strs + 'b'
    else:
        strs = strs + 'c'

sys.stdout.write(strs)

以下函数将使用 set() 而不是列表来完成关键更改,这会将运行时间从 O(len(a) * len(b)) 减少到 O(len(a))

其他一些更改是对数组长度的一些检查,您需要执行这些检查以确保您的索引不会超出数组范围。

import sys

# what do you need z for?
# this will only cause problems, you can use len() instead to get the lenght of the string
# z = int(input())
a = input("Please enter string a: ")
b = input("Please enter string b: ")


def compare_strs(a, b):
    strs = ''
    # no need for this here as range will start at 0 by default
    # i = 0
    # set will have constant lookup time O(1)
    lookupCharacters = set(a)
    for i in range(len(a)):
        # you need to make sure the index is in bounds of the array here!
        if i < len(b):
            if b[i] == a[i]:
                strs = strs + 'a'
            # this will now lookup in the set which takes O(1) and not O(len(a))
            elif b[i] in lookupCharacters:
                strs = strs + 'b'
        strs = strs + 'c'
        # no need for this here as range() will automatically increase i for the next iteration
        # i = i + 1
    sys.stdout.write(strs)


compare_strs(a, b)