2021年11月2日 星期二

[LeetCode] 1002. Find Common Characters

轉自LeetCode

Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.

 

Example 1:

Input: words = ["bella","label","roller"]
Output: ["e","l","l"]

Example 2:

Input: words = ["cool","lock","cook"]
Output: ["c","o"]

 

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists of lowercase English letters.

Solution


這題是 349. Intersection of Two Arrays 和 350. Intersection of Two Arrays II 的衍生

主要差別是要從多個比較對象裡面找到交集的所有字元,包含重複字元

所以在作法上有點修正

這次每個 word 都用一個 IntArray(26) 去記錄 a到z中,每個字元出現的次數

然後過程中,也紀錄每個字元最少出現的次數

如果有一個字元在某個 word 沒出現,那麼最後的值一定要是 0,因為不符合要找的

如果有一個字元都有在每個 word 出現,那次數要取最小的

最後再拼裝成答案就行

kotlin

沒有留言:

張貼留言