1002. Find Common Characters
Easy
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:
class Solution {
/**
* @param String[] $words
* @return String[]
*/
function commonChars($words) {
$letterCount = array_fill(0, 26, PHP_INT_MAX);
foreach ($words as $word) {
$wordLetterCount = array_fill(0, 26, 0);
foreach (str_split($word) as $letter) {
++$wordLetterCount[ord($letter) - ord('a')];
}
for ($i = 0; $i < 26; ++$i) {
$letterCount[$i] = min($letterCount[$i], $wordLetterCount[$i]);
}
}
$result = [];
for ($i = 0; $i < 26; ++$i) {
while ($letterCount[$i] > 0) {
$result[] = chr($i + ord('a'));
--$letterCount[$i];
}
}
return $result;
}
}
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me: