809. Expressive Words
Example:
Input:
S = "heeellooo"
words = ["hello", "hi", "helo"]
Output: 1
Explanation:
We can extend "e" and "o" in the word "hello" to get "heeellooo".
We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more.bool isExpressive(const string& S, const string& word) { // time: O(m + n)
int m = S.length(), n = word.length();
int i1 = 0, i2 = 0, j1 = 0, j2 = 0;
for (; i1 < m && j1 < n; i1 = i2, j1 = j2) {
if (S[i1] != word[j1]) return false;
while (i2 < m && S[i2] == S[i1]) ++i2;
while (j2 < n && word[j2] == word[j1]) ++j2;
int i_len = i2 - i1, j_len = j2 - j1;
if (i_len != j_len && i_len < max(3, j_len)) return false;
}
return i1 == m && j1 == n;
}
int expressiveWords(string S, vector<string>& words) { // time: O(# of words * S_len * avg_word_len)
int res = 0;
for (const string& word : words) {
if (isExpressive(S, word)) ++res;
}
return res;
}Last updated