这是一道简单题,但是我也会尽可能的把它做好,代码提及已经通过,但是我自己产生一个疑惑。下面是我第一次提交的代码(耗时 64ms):
class Solution:
def canConstruct(self, ransomNote, magazine):
rans = ransomNote.replace('', ' ').split()
mags = magazine
for i in range(len(ransomNote)):
if rans[i] in mags:
mags = mags.replace(rans[i], '',1)
rans[i] = ''
if not ''.join(rans):
return True
return False
可以看到,mags 对 magazine 做了引用,然后,修改代码如下:
class Solution:
def canConstruct(self, ransomNote, magazine):
rans = ransomNote.replace('', ' ').split()
for i in range(len(ransomNote)):
if rans[i] in mags:
magazine = magazine.replace(rans[i], '',1)
rans[i] = ''
if not ''.join(rans):
return True
return False
再次提交后,代码耗时达到 96ms。 按道理,引用虽然没开辟新内存,但耗时相差也不会这么大啊,求解。