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

前端 未结 10 1979
醉酒成梦
醉酒成梦 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:06

    Here is a rough idea that should work.

    1. Copy the source string into a new string
    2. While the copy string still has data and there are still substrings a. Grab a sub string, if copy.contains(substr) copy.remove(substr)
    3. If the copy is now empty then yes, you could construct the string
    4. If copy is not empty, throw out the first substr that was removed from the string and repeat.
    5. If all substrings are gone and copy is still not empty then no, you can't construct it.

    Edit: A way to possibly improve this would be to first iterate all of the substrings and throw out any that are not contained in the main string. Then go through the above steps.

提交回复
热议问题