Advertisement
Guest User

Untitled

a guest
Apr 12th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. I interpret the requirements as "find all non-overlapping substring pairs `p + q` of string `s` that combine to form a palindrome".
  2.  
  3. There are three base cases.
  4.  
  5. 1. len(p) == 1 and len(q) == 1, e.g. `A + A -> AA`
  6. 2. len(p) == 1 and len(q) == 2, e.g. `B + CB -> BCB`
  7. 3. len(p) == 2 and len(q) == 1, e.g. `DE + D -> DED`
  8.  
  9. And there is one inductive case.
  10.  
  11. 4. if len(p) >= 2 and len(q) >= 2, then p+q can only be a solution if p[1:] + q[:-1] is a solution.
  12.  
  13. Outline of algorithm:
  14.  
  15. Create an empty set `pairs` that will contain tuples of length two. Each tuple represents a p+q pair. Each element of the tuple is a slice object.
  16.  
  17. Iterate through the string and construct a dictionary `d` that maps each character to a list of all that character's indices in the string.
  18. Elements belonging to the same list can be paired together to satisfy case #1. Add them to `pairs`.
  19.  
  20. Iterate through all length-two slices of the string. For each slice `r`:
  21. find all entries in the dictionary with key `r[-1]` that don't overlap r's position. Those entries, paired with r, comprise all case #2 pairs. Add them to `pairs`.
  22. find all entries in the dictionary with key `r[0]` that don't overlap r's position. Those entries, paired with r, comprise all case #3 pairs. Add them to `pairs`.
  23.  
  24. create an empty set called `case_4_pairs`.
  25. For each `p` and `q` slice pair in `pairs`:
  26. decrease the lower bound of p by one, and increase the upper bound of q by one. If these new slices do not overlap, and if they are still in `s`'s range, and if the new characters match, p_new + q_new is a case #4 palindrome. Add them to `case_4_pairs`.
  27. Continue changing p and q's boundaries until the new slices fail to make a valid pair.
  28.  
  29. You're done. The solution is the union of `pairs` and `case_4_pairs`.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement