问题
This is description of my problem:

- I was thinking about start from left and add one letter and if it's word then check rest if could be separated to words (call recursion function). If yes then I have result if not then I would add one more letter to first word and so on. But this would take first smaller words and I guess it's needed to start with algorithm which check first longer words and then smaller.
- So I was thinking about start with whole word and then recursively check left part without last letter and then right part. If it wouldn't return true then I moved to left with "cursor" and then check left part without 2 last letters and right part (from 2 last letters) and so on. But I think this would required more time then O(n^2).
So can someone help me with basic algoritm which would work and satisfy time complexity? Thanks
回答1:
The dynamic programming approach could be based on the following recursive formula:
f(n) = true
f(i) = OR { d(s[i]s[i+1]...s[j-1]) AND f(j) | for each j such that i < j <= n }
Start from f(0).
Explanation:
If you got to the end of the string - you're good (base clause).
Otherwise, try to split the word wherever you can from the given start (which is i
), and recursively invoke on the suffix of the string.
Complexity is actually O(n^2 * g(n))
where g(n)
is the time it takes for dict
to check if the word is in it. (Every solution need to depend on it somehow...)
Converting to DP solution:
Fill the table from last to first, according to the logic described in the recursive formula.
回答2:
Simple solution in O(n^2) will be :-
DP(n) = (DP(0) && dict(S[1..n]) || (DP(1) && dict(S[2..n]))..... || (DP(n-1) && dict(S[n..n])
DP(0) = true
DP(n) = Whether there is valid sentence made from S[1...n]
S[i...j] is substring from ith index to jth index
来源:https://stackoverflow.com/questions/22917717/dynamic-programming-algorithm-to-repair-text-where-is-all-punctuation-missing