我正在尝试解决Hackerrank问题:为给定的字符串输入找到下一个按字典顺序更大的字符串排列。
这是我的解决方法:
def biggerIsGreater(w):
if len(w)<=1: return w
# pair letters in w string with int representing positional index in alphabet
letter_mapping = dict(zip(string.ascii_lowercase, range(1, len(string.ascii_lowercase)+1)))
char_ints = [letter_mapping[letter] for letter in w.lower() if letter in letter_mapping]
# reverse it
reversed_char_ints = char_ints[::-1]
# get char set to reorder, including pivot.
scanned_char_ints = []
index = 0
zipped = list(zip(reversed_char_ints, reversed_char_ints[1:]))
while index < len(zipped):
char_tuple = zipped[index]
scanned_char_ints.append(char_tuple[0])
if char_tuple[0] <= char_tuple[1]:
if index == len(zipped) - 1:
return "no answer"
else:
scanned_char_ints.append(char_tuple[1])
break
index += 1
# get smallest among bigger values of pivot
char_to_switch = None
char_to_switch_index = None
for item in scanned_char_ints[:-1]:
if item > scanned_char_ints[-1]:
if char_to_switch == None or item <= char_to_switch:
char_to_switch = item
char_to_switch_index = scanned_char_ints.index(item)
# switch pivot and smallest of bigger chars in scanned chars
pivot_index = len(scanned_char_ints) - 1
scanned_char_ints[pivot_index], scanned_char_ints[char_to_switch_index] = scanned_char_ints[char_to_switch_index], scanned_char_ints[pivot_index]
# order from second to end the other chars, so to find closest bigger number of starting number
ord_scanned_char_ints = scanned_char_ints[:-1]
ord_scanned_char_ints.sort(reverse=True)
ord_scanned_char_ints.append(scanned_char_ints[-1])
# reverse scanned chars
ord_scanned_char_ints.reverse()
# rebuild char int list
result_ints = char_ints[:len(char_ints) - len(ord_scanned_char_ints)]
result_ints.extend(ord_scanned_char_ints)
result_ = ""
for char_intx in result_ints:
for char, int_charz in letter_mapping.items():
if int_charz == char_intx:
result_ += char
return result_
(我知道互联网上有解决方案,可以用更简洁的方式解决问题,但我显然很想自己成功)。 现在,它似乎可以运行1、2、100个最多100个字符的字符串输入。 但是,当hackerrank测试过程针对最多100个字母的100000个字符串进行测试时,将导致错误,并且没有关于它的更多信息。在我的机器上运行具有类似输入大小的测试不会引发任何错误。
此解决方案有什么问题?
预先感谢