我在一次面试中被问到这个HC问题。我想出了一个我称之为蛮力的方法。下面是问题说明:
我的逻辑:查找给定字符串中的所有分散回文,"aabb"的子字符串可以分散,但可以重新排列以形成回文。示例:a, aa, aab, aabb, a, abb, b, bb, bba和b是子字符串
divide the str into substrings
counter = 0
if the len(substr) is even:
and substr == reverse(substr)
increment counter
else:
store all the number of occurrences of each str of substr in a dict
process dict somehow to figure out if it can be arranged into a palindrome
###### this is where I ran out of ideas ######
我代码:class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
c=0
for i in range(0,n-1): #i=0
print('i:',i)
for j in range(i+1,n+1): #j=1
print('j',j)
temp = s[i:j]
if len(temp) == 1:
c+=1
# if the len of substring is even,
# check if the reverse of the string is same as the string
elif(len(temp)%2 == 0):
if (temp == temp[::-1]):
c+=1
print("c",c)
else:
# create a dict to check how many times
# each value has occurred
d = {}
for l in range(len(temp)):
if temp[l] in d:
d[temp[l]] = d[temp[l]]+1
else:
d[temp[l]] = 1
print(d)
return c
op = Solution()
op.countSubstrings('aabb')
到现在,很明显我是一个初学者。我相信有更好,更复杂的方法来解决这个问题。我的一些代码改编自visleck的逻辑,我无法跟上它的后半部分。如果有人能解释一下,那就太好了。
作为部分答案,字符串是否为分散回文的测试很简单:如果出现奇数次的字母的数量最多为1,则它是一个分散回文。否则就不是。
可以这样实现:
from collections import Counter
def scattered_palindrome(s):
counts = Counter(s)
return len([count for count in counts.values() if count % 2 == 1]) <= 1
例如,>>> scattered_palindrome('abb')
True
>>> scattered_palindrome('abbb')
False
注意,在任何阶段都不需要将一个字符串与其反向字符串进行比较。另外,请注意,我使用了一个Counter对象来跟踪字母计数。这是一种创建类似字典的字母计数集合的简化方法。