他人解法:
其实思路和我的想法一致——计算子串中出现次数为单数的字符种类的总数m,最小使为回文序列的k必满足:k * 2 >= m - (j - i + 1)。但不同之处在于,“字典”的构建方法。我在若干次time limit exceeds后,想为字符串建立查找表,键为(起始位置,终止位置),值为最小k,然而该方法势必在建表阶段时间复杂度、空间复杂度为及以上,唯一优势是在查找次数较多时有更好的性价比。
然而本文建立的“查找表”方法非常简洁,起始位置均为0,为每个结束位置建立一个列表形式的“字典”,而且形式只能是列表。以列表形式建立“字典”之后,任意位置的字符串可以由两个字典相减得到。时间复杂度为,空间复杂度为
。
class Solution(object):
def canMakePaliQueries(self, s, queries):
cur, count = [0] * 26, [[0] * 26]
answer = []
for c in s:
cur[ord(c) - ord('a')] += 1
count.append(cur[:])
for i, j, k in queries:
m = 0
print(s[i: j + 1])
print(k)
for a, b in zip(count[i], count[j + 1]):
print(a, b)
m += (b - a) % 2
if m - (j - i + 1) % 2 <= k * 2:
answer.append(True)
else:
answer.append(False)
return answer
我的解法:
Time Limit Exceeds
class Solution(object):
def canMakePaliQueries(self, s, queries):
"""
:type s: str
:type queries: List[List[int]]
:rtype: List[bool]
"""
answer = []
k_map = {}
i = 0
while i <= len(s) - 1:
j = i
char_map = {}
while j <= len(s) - 1:
if s[j] in char_map:
char_map[s[j]] += 1
if j > i:
if self.is_odd(char_map[s[j]]):
if not self.is_odd(j - i + 1):
k_map[(i, j)] = k_map[(i, j - 1)] + 1
else:
k_map[(i, j)] = k_map[(i, j - 1)]
else:
if not self.is_odd(j - i + 1):
k_map[(i, j)] = k_map[(i, j - 1)]
else:
k_map[(i, j)] = max(k_map[(i, j - 1)] - 1, 0)
else:
k_map[(i, j)] = 0
else:
char_map[s[j]] = 1
if j > i:
if self.is_odd(j - i + 1):
k_map[(i, j)] = k_map[(i, j - 1)]
else:
k_map[(i, j)] = k_map[(i, j - 1)] + 1
else:
k_map[(i, j)] = 0
j += 1
i += 1
for query in queries:
print(s[query[0]: query[1]+1])
print('k = '+str(query[2]))
if k_map[(query[0], query[1])] > query[2]:
answer.append(False)
print(False)
else:
answer.append(True)
print(True)
return answer
def is_odd(self, number):
"""
:type number: int
:rtype: int
"""
if number % 2 != 0:
return True
else:
return False
solution = Solution()
num = solution.canMakePaliQueries()
print(num)