【发布时间】:2020-03-12 05:34:30
【问题描述】:
我正在解决以下问题:
我受到the first answer to this question 的启发,想出了一个解决方案,该解决方案利用 XOR(恒等、交换和自逆)的一些属性在 O(n) 时间和 O(1) 空间中工作。
def checkInclusion(s1: str, s2: str) -> bool:
# Checks for permutation of s1 inside of s2.
# Xor's all of the characters in a s1-length window of s2
# If xor_product = 0 --> permutation identified
# Relies on properties of xor to find answer: identity, communtative, and self-inverse
xor_product = 0
for i in range(0, len(s2) - len(s1) + 1):
s1_index = 0
for j in range(i, i + len(s1)):
xor_product = xor_product ^ ord(s1[s1_index]) ^ ord(s2[j])
s1_index += 1
if xor_product == 0: return True
xor_product = 0
return False
此解决方案适用于大多数输入,但在 s1 = "kitten" 和 s2 = "sitting" 时失败。这个解决方案在概念上是否存在缺陷?如果是这样,那怎么办?如果不是,那是什么错误?
诚然,我对编码面试风格问题很陌生。感谢所有帮助。
【问题讨论】:
-
你试过调试了吗?你的发现在哪里?
-
@MrSmith42 是的。尽管我尝试了一切,但问题仍然存在。我强烈怀疑异或方法在概念上存在缺陷,但我想了解原因。除非我要使用更复杂的散列方法,否则我想在 O(1) 空间中没有办法做到这一点。
标签: python algorithm xor bitwise-xor