For the N-to-N case, use a trie or prefix tree.
In reply to Re: String matching idea by salva in thread String matching idea by baxy77bax