【发布时间】:2017-02-09 22:47:24
【问题描述】:
我需要找到使字符串排序所需的最小删除次数。
示例测试用例:
# Given Input:
teststr = "abcb"
# Expected output:
1
# Explanation
# In this test case, if I delete last 'b' from "abcb",
# then the remaining string "abc" is sorted.
# That is, a single deletion is required.
# Given Input:
teststr = "vwzyx"
# Expected output:
2
# Explanation
# Here, if I delete 'z' and 'x' from "vwzyx",
# then the remaining string "vwy" is a sorted string.
我尝试了以下方法,但它给出了超出时间限制的错误。 有其他方法解决这个问题吗?
string = input()
prev_ord = ord(string[0])
deletion = 0
for char in string[1:]:
if ord(char) > prev_ord +1 or ord(char) < prev_ord:
deletion += 1
continue
prev_ord = ord(char)
print(deletion)
【问题讨论】:
-
这个问题有一个非常好的 Python 实现,称为Longest increasing subsequence 问题(这里)[stackoverflow.com/questions/3992697/…
-
感谢您找到那个欺骗目标,@chthonicdaemon。
-
我在我的答案中添加了一个更更有效的版本。
-
任何人都可以帮助解决这个问题的java版本