Algorithm for checking if a string was built from a list of substrings

前端 未结 10 1973
醉酒成梦
醉酒成梦 2021-02-02 14:35

You are given a string and an array of strings. How to quickly check, if this string can be built by concatenating some of the strings in the array?

This is a theoretica

10条回答
  •  北海茫月
    2021-02-02 15:07

    It's definitely not quick but you here's an idea:

    • Iterate over all the strings, checking if the target string "begins" with any of them
    • Take the longest string with which the target string begins, remove it from the list and trim it from the main string
    • Rinse, repeat

    Stop when you're left with a 0 length target string.

    As I said before, this is definitely not fast but should give you a baseline ("it shouldn't get much worse than this").

    EDIT

    As pointed out in the comments, this will not work. You will have to store the partial matches and fall back on them when you find there is no way further.

    • When you find that a string is the head of the target, push it onto a list. After building the list, you will naturally try the biggest "head" of the target
    • When you find that the head you tried doesn't fit with what's left, try the next best head

    This way, eventually you'll explore the entire space of solutions. For every candidate head you'll try every possible tail.

提交回复
热议问题