Friday, December 7, 2018

809. Expressive Words

809Expressive Words
Sometimes people repeat letters to represent extra feeling, such as "hello" -> "heeellooo", "hi" -> "hiiii".  Here, we have groups, of adjacent letters that are all the same character, and adjacent characters to the group are different.  A group is extended if that group is length 3 or more, so "e" and "o" would be extended in the first example, and "i" would be extended in the second example.  As another example, the groups of "abbcccaaaa" would be "a", "bb", "ccc", and "aaaa"; and "ccc" and "aaaa" are the extended groups of that string.
For some given string S, a query word is stretchy if it can be made to be equal to S by extending some groups.  Formally, we are allowed to repeatedly choose a group (as defined above) of characters c, and add some number of the same character c to it so that the length of the group is 3 or more.  Note that we cannot extend a group of size one like "h" to a group of size two like "hh" - all extensions must leave the group extended - ie., at least 3 characters long.
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 extended.
Notes:
  • 0 <= len(S) <= 100.
  • 0 <= len(words) <= 100.
  • 0 <= len(words[i]) <= 100.
  • S and all words in words consist only of lowercase letters
-----------------
又又又一道说不清题意题

解法:
对字母每次出现的连续次数(个数)做对比
一些例子:
fffe, ffe -> true
fffe,fffe -> true
ffe, fe -> false
ffe, ffe -> true
O(m * n)
class Solution {
    public int expressiveWords(String S, String[] words) {
        int count = 0;
        for (String w : words) {
            if (helper(S, w)) count++;
        }
        
        return count;
    }
    
    private boolean helper(String s, String w) {
        int i = 0, j = 0;
        int m = s.length(), n = w.length();
        
        while (i < m && j < n) {
            char c1 = s.charAt(i);
            char c2 = w.charAt(j);
            
            if (c1 != c2) return false;
            int count1 = getCount(s, i);
            int count2 = getCount(w, j);
            
            if ((count1 == 2 && count2 == 1) 
                || (count1 < count2)) return false;
            i += count1;
            j += count2;
        }
        
        
        return i == m && j == n;
    }
    
    private int getCount(String s, int i) {
        int count = 1;
        i++;
        while (i < s.length()) {
            if (s.charAt(i) == s.charAt(i - 1)) count++;
            else break;
            i++;
        }
        
        return count;
    }
}

No comments:

Post a Comment