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

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

    two options sprint to mind but neither of them seem very elegant.

    1) brute force: do it like you would a password generator i.e. word1+word1+word1 > word1+word1+word2 > word1+word1+word3 etc etc etc

    the trick there is the length so youd have to try all combinations of 2 or more words and you don't know where to set the limit. Very time consuming.

    2) take the string in question and run a find in on it for every word you have 1 at a time. maybe check the length and if its greater than 0 do it again. keep doing it till you hit zero it cant find any more results. if you hit 0 its a win if not its a lose. I think this method would be a lot better than the first but I imagine someone will have a better suggestion.

提交回复
热议问题