Expressive Words

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.

Example: 
the Input:  
S = "heeellooo" 
words = [ "Hello", "Hi", "HELO"] the Output: . 1
 Explanation: 
We CAN Extend "E" and "O" in The Word "Hello" to GET "heeellooo" . 
We CAN not Extend "the HELO" to GET "heeellooo" Because at the Group "LL" iS not size 3 or More. 
ideas: google high frequency, when I write is to use a double pointer, but the space is very expensive, but after I read the answer, indeed concise wording, can handle two string with two pointers respectively. Really learn a lot, the same ideas, write the code is not the same;
 
class Solution {
    public int expressiveWords(String S, String[] words) {
        if(S == null || words == null || words.length == 0) {
            return 0;
        }
        int count = 0;
        for(String word : words) {
            if(isStretchy(S, word)) {
                count++;
            }
        }
        return count;
    }
    
    private boolean isStretchy(String S, String word) {
        int i = 0; int j = 0;
        while(i < S.length() && j < word.length()) {
            int scount = 1;
            while(i + 1 < S.length() && S.charAt(i) == S.charAt(i+1)) {
                scount++;
                i++;
            }
            
            int wcount = 1;
            while(j + 1 < word.length() && word.charAt(j) == word.charAt(j+1)) {
                wcount++;
                j++;
            }
            if(i < S.length() && j < word.length() && S.charAt(i) == word.charAt(j)) {
                if(scount == wcount || (scount >= 3 && scount > wcount )) {
                    i++;
                    j++;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }
        return i == S.length() && j == word.length();
    }
}

 

Published 673 original articles · won praise 13 · views 180 000 +

Guess you like

Origin blog.csdn.net/u013325815/article/details/105220384
Recommended