Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- I interpret the requirements as "find all non-overlapping substring pairs `p + q` of string `s` that combine to form a palindrome".
- There are three base cases.
- 1. len(p) == 1 and len(q) == 1, e.g. `A + A -> AA`
- 2. len(p) == 1 and len(q) == 2, e.g. `B + CB -> BCB`
- 3. len(p) == 2 and len(q) == 1, e.g. `DE + D -> DED`
- And there is one inductive case.
- 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.
- Outline of algorithm:
- 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.
- 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.
- Elements belonging to the same list can be paired together to satisfy case #1. Add them to `pairs`.
- Iterate through all length-two slices of the string. For each slice `r`:
- 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`.
- 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`.
- create an empty set called `case_4_pairs`.
- For each `p` and `q` slice pair in `pairs`:
- 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`.
- Continue changing p and q's boundaries until the new slices fail to make a valid pair.
- You're done. The solution is the union of `pairs` and `case_4_pairs`.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement