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.

```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.
```

Constraints:

• `0 <= len(S) <= 100`.
• `0 <= len(words) <= 100`.
• `0 <= len(words[i]) <= 100`.
• `S` and all words in `words` consist only of lowercase letters

809. Expressive Words
``````struct Solution;

struct Word {
data: Vec<(char, usize)>,
}

impl Word {
fn new(s: String) -> Self {
let mut data = vec![];
let mut prev: Option<(char, usize)> = None;
for c in s.chars() {
if let Some(p) = prev {
if c == p.0 {
prev = Some((c, p.1 + 1));
} else {
data.push(p);
prev = Some((c, 1));
}
} else {
prev = Some((c, 1));
}
}
if let Some(p) = prev {
data.push(p);
}
Word { data }
}

fn stretchy(&self, word: &Word) -> bool {
let n = self.data.len();
let m = word.data.len();
if n != m {
return false;
}
for i in 0..n {
let p = self.data[i];
let q = word.data[i];
if p.0 != q.0 || p.1 > q.1 || (q.1 < 3 && p.1 != q.1) {
return false;
}
}
true
}
}

impl Solution {
fn expressive_words(s: String, words: Vec<String>) -> i32 {
let word = Word::new(s);
let words: Vec<Word> = words.into_iter().map(Word::new).collect();
words.iter().filter(|w| w.stretchy(&word)).count() as i32
}
}

#[test]
fn test() {
let s = "heeellooo".to_string();
let words = vec_string!["hello", "hi", "helo"];
let res = 1;
assert_eq!(Solution::expressive_words(s, words), res);
}
``````