809. Expressive Words



Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii". In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo".
For some given string S, 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 3 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 size less than 3. 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.
Given a list of query words, return the number of words that are stretchy.
S = "heeellooo"
words = ["hello", "hi", "helo"]
Output: 1
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.
0 <= len(S) <= 100.
0 <= len(words) <= 100.
0 <= len(words[i]) <= 100.
S and all words in words consist only of lowercase letters


Approach #1 Run Length Encoding

Time: O(QK) && Space: O(K)
where Q is the length of words (at least 1), and K is the maximum length of a word.)
class Solution {
public int expressiveWords(String S, String[] words) {
RLE R = new RLE(S);
int ans = 0;
search: for (String word: words) {
RLE R2 = new RLE(word);
if (!R.key.equals(R2.key)) continue;
for (int i = 0; i < R.counts.size(); i++) {
int c1 = R.counts.get(i);
int c2 = R2.counts.get(i);
if (c1 < 3 && c1 != c2 || c1 < c3) {
continue search;
return ans;
class RLE {
String key;
List<Integer> counts;
public RLE(String S) {
StringBuilder sb = new StringBuilder();
counts = new ArrayList();
char[] ca = S.toCharArray();
int N = ca.length;
int prev = -1;
for (int i = 0; i < N; i++) {
if (i == N - 1 || ca[i] != ca[i+1]) {
counts.add(i - prev);
prev = i;
key = sb.toString();