Given an array of string words
, please design a string subsequence matcher.
Implement the SubsequenceMatcher
class:
SubsequenceMatcher(string words[])
: Initializes the object with a pattern arraywords
, and an empty strings
.bool addChar(char c)
: Add a characterc
to the end of the strings
. Returntrue
if at least one string inwords
is a subsequence ofs
,false
otherwise.
Example:
words = ["abc", "bd", "ace"]
addChar('a') -> false // a
addChar('d') -> false // ad
addChar('b') -> false // adb
addChar('e') -> false // adbe
addChar('c') -> true // adbec, include a subsequence abc
The aim is to minimize the cost of each call to addChar
. I find a similar problem leetcode 795, the solution is O(n)
for an addChar
call, where n
is the length of words
. Is there a more efficient algorithm?