算法總結 - 字符串 - 字符壓縮與延伸

算法總結 - 字符串 - 字符壓縮與延伸

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.


Abstract

  • 給出了一個字符串,其中有些字母是爲了表現“情緒”而重複出現了多次
  • 給出了一個字符串數組,求有多少個字符串可以產生這樣的情緒化詞
  • 表現語氣最少需要一個字母重複三次。

Idea

  • 簡化情緒化次或者延伸候選字符串

Question to ask

  • 怎麼化簡一個情緒詞?

Solution

  • 把情緒詞和候選字符串每個字符依次對比, 一下情況不能構造情緒詞
    • 字符相同, 情緒詞重複字符的次數小於3且不等於候選字符串重複次數
    • 字符相同,情緒詞重複字符次數小於候選字符串次數
    • 字符不同

Code

public int expressiveWords(String S, String[] words) {
  int cnt = 0;
  
  for (String s: words){
  		// m1
      if (helper(S, s)) cnt++;
  }
  return cnt;
}

private boolean helper(String s, String t){
  int i = 0;
  int j = 0;
  
  while(i < s.length() && j < t.length()){
      char cs = s.charAt(i);
      char ct = t.charAt(j);
      int ls = getLen(s, i);
      int lt = getLen(t, j);
      
      if (cs == ct){
          if ((ls < 3 && ls != lt) || lt > ls){
              return false;
          }
      }else{
          return false;
      }
      i = i + ls;
      j = j + lt;
  }
  
  // m2
  return i == s.length() && j == t.length();
}

private int getLen(String s, int i){
  int j = i;
  while(j < s.length() && s.charAt(j) == s.charAt(i)){
      j++;
  }
  return j - i;
}

Time Complexity
O(nl): n 候選詞個數, l 最長候選詞的長度

Space Complexity
O(1)

Mistake

  1. 單純把所有的重複字符簡化成一個字符不能通過一下的測試用例
    • "zzzzzyyyyy"和[“zzyy”,“zy”,“zyy”]
    • "heeellooo"和 [“hello”, “hi”, “helo”]
  2. 簡化時要確保檢查在情緒詞和候選詞中的每個字符,別忘記最後的字符

Summary

  • 分情況考慮問題
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章