我正在尝试编写一段Python代码来解决一个问题:完成下面的gameOfThrones函数,以确定给定的字符串是否可以重新排列为回文。如果可能,返回YES,否则返回NO。
我的逻辑是,如果输入字符串的长度是偶数,那么字符串中的所有字符数都必须是偶数。但是,如果字符串的长度为奇数,则除一个字符为奇数外,所有字符都必须具有偶数个字符。
我写的代码如下:
def gameOfThrones(s):
d = {}
s = sorted(s)
count = 0
for i in s:
if i not in d:
d[i] = 1
else:
d[i] += 1
if len(s) % 2 == 0:
for v in d.values():
if v % 2 != 0:
print("NO")
else:
print("YES")
else:
for v in d.values():
if v % 2 == 1:
count += 1
if count > 1:
print("NO")
elif count == 1:
print("YES")我不确定我哪里出错了。代码对我来说似乎是有意义的。请协助,谢谢您的帮助。
发布于 2020-04-18 14:29:44
我试着用2个测试运行你的代码,如下所示:
def gameOfThrones(s):
d = {}
s = sorted(s)
count = 0
for i in s:
if i not in d:
d[i] = 1
else:
d[i] += 1
if len(s) % 2 == 0:
for v in d.values():
if v % 2 != 0:
print("NO")
else:
print("YES")
else:
for v in d.values():
if v % 2 == 1:
count += 1
if count > 1:
print("NO")
elif count == 1:
print("YES")
gameOfThrones("aabb")
gameOfThrones("aabbbccc")
# output
YES
YES
NO
NO
YES如您所见,您的代码为2个测试输出了5个答案。
代码中的2个问题:在偶数长度的s中找到奇数字符后不会中断,并且在偶数长度的s中找到偶数字符时会打印过多的"YES“。
if len(s) % 2 == 0:
for v in d.values():
if v % 2 != 0:
print("NO") // break
else:
print("YES") // incorrect logichttps://stackoverflow.com/questions/61284795
复制相似问题