[LC] 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.

class Solution {
    public int expressiveWords(String S, String[] words) {
        int res = 0;
        for (String word: words) {
            if (stretchy(S, word)) {
                res += 1;
            }
        }
        return res;
    }
    
    private boolean stretchy(String S, String word) {
        int i = 0, j = 0;
        while (i < S.length() && j < word.length()) {
            if (S.charAt(i) != word.charAt(j)) {
                return false;
            }
            int lenS = getRepeated(i, S);
            int lenWord = getRepeated(j, word);
            if (lenS < 3 && lenWord != lenS || lenS >= 3 && lenS < lenWord) {
                return false;
            }
            i += lenS;
            j += lenWord;
        }
        return i == S.length() && j == word.length();
    }
    
    private int getRepeated(int index, String word) {
        int i = index;
        while (i < word.length() && word.charAt(i) == word.charAt(index)) {
            i += 1;
        }
        return i - index;
    }
}

 

posted @ 2020-02-11 11:40  xuan_abc  阅读(141)  评论(0编辑  收藏  举报