[LeetCode] 809. Expressive Words

809. Expressive Words

Sometimes people repeat letters to represent extra feeling. For example:

  • “hello” -> “heeellooo”
  • “hi” -> “hiiii”

In these strings like “heeellooo”, we have groups of adjacent letters that are all the same: “h”, “eee”, “ll”, “ooo”.

You are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is three or more.

  • For example, starting with “hello”, we could do an extension on the group “o” to get “hellooo”, but we cannot get “helloo” since the group “oo” has a size less than three. Also, we could do another extension like “ll” -> “lllll” to get “helllllooo”. If s = “helllllooo”, then the query word “hello” would be stretchy because of these two extension operations: query = “hello” -> “hellooo” -> “helllllooo” = s.

Return the number of query strings that are stretchy.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
bool equal(char a, char b, char c) {
return a == b && b == c;
}
bool compare(string& s, string &w) {
int j(0), slen(s.length()), wlen(w.length());
for(int i(0);i < slen; i++) {
if(s[i] == w[j] and j < wlen) j++;
else if(0 < i and i < slen - 1 and equal(s[i - 1], s[i], s[i + 1]));
else if(i > 1 and equal(s[i - 2], s[i - 1], s[i]));
else return false;
}
return j == wlen;
}
public:
int expressiveWords(string s, vector<string>& words) {
int res(0);
for(auto& w : words) {
if(compare(s, w)) ++res;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/10/PS/LeetCode/expressive-words/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.