Scan the string from left to right. At the current position, choose the longest given word that matches. Increment its count and advance by its length.
Specifically, test gugugaga, guguga, gugaga, and guga in that order, and choose the first match. The two words of equal length may be checked in either order. Since the input is a concatenation of the four words, at least one word can always be found.
Longer words must be considered first because guga is a prefix of gugaga, and guguga is a prefix of gugugaga. Choosing the shorter word first would leave ga to be incorrectly treated as the start of the next word.
There are only four words, each of length at most , so finding the next word takes constant time. The time complexity is therefore . Storing the input string uses space, while the four counters and the current position require additional space.
Proof
Let be the actual first word in the unprocessed part of the string. Since matches at the current position, the longest matching word chosen by the algorithm cannot be shorter than .
If were longer than , then would be a proper prefix of . Among the given words, this happens only in the following two cases:
Solution written by GPT6
gugaga is guga followed by ga.gugugaga is guguga followed by ga.Thus, incorrectly choosing a longer word would require the two characters immediately after the actual word to be ga. If is the last word, there are no characters after it. Otherwise, the next word starts with gu. Neither case allows ga to follow, so .
After removing this correctly identified word, the remaining string is again a concatenation of the same four words. Repeating the argument proves that every word is identified correctly, so all four counts are correct. It also shows that the decomposition into words is unique.