LeetCode – Expressive Words (Java)

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.

Java Solution

This problem is similar to regular expression matching.

public int expressiveWords(String S, String[] words) {
    int count = 0;
    for (String s : words) {
        if (isMatch(S, 0, s, 0)) {
            count++;
        }
    }
 
    return count;
}
 
private boolean isMatch(String s1, int i, String s2, int j) {
    if (i >= s1.length() && j >= s2.length()) {
        return true;
    } else if (i >= s1.length() || j >= s2.length()) {
        return false;
    }
 
    if (s1.charAt(i) != s2.charAt(j)) {
        return false;
    }
 
    boolean res = false;
 
    if (i + 2 < s1.length()
            && s1.charAt(i + 1) == s2.charAt(j)
            && s1.charAt(i + 2) == s2.charAt(j)) {
        int m = i + 2;
        int n = j + 1;
        while (m < s1.length() && s1.charAt(m) == s2.charAt(j)) {
            m++;
        }
        while (n < s2.length() && s2.charAt(n) == s2.charAt(n - 1)) {
            n++;
        }
        if (n - j > m - i) {
            return false;
        }
 
        res = isMatch(s1, m, s2, n);
    }
 
    res = res | isMatch(s1, i + 1, s2, j + 1);
 
    return res;
}

Leave a Comment