|
| 1 | +<?php |
| 2 | +class Solution |
| 3 | +{ |
| 4 | + /** |
| 5 | + * @param String $paragraph |
| 6 | + * @param String[] $banned |
| 7 | + * @return String |
| 8 | + */ |
| 9 | + public function mostCommonWord($paragraph, $banned) |
| 10 | + { |
| 11 | + $paragraph = strtolower($paragraph); |
| 12 | + |
| 13 | + $words = preg_split('/\W+/', $paragraph, -1, PREG_SPLIT_NO_EMPTY); |
| 14 | + |
| 15 | + $wordCount = []; |
| 16 | + |
| 17 | + $bannedWords = array_flip($banned); |
| 18 | + |
| 19 | + $maxCount = 0; |
| 20 | + |
| 21 | + $mostCommonWord = ""; |
| 22 | + |
| 23 | + foreach ($words as $word) { |
| 24 | + |
| 25 | + if (isset($bannedWords[$word])) { |
| 26 | + continue; |
| 27 | + } |
| 28 | + if (! isset($wordCount[$word])) { |
| 29 | + $wordCount[$word] = 0; |
| 30 | + } |
| 31 | + |
| 32 | + $wordCount[$word]++; |
| 33 | + |
| 34 | + if ($wordCount[$word] > $maxCount) { |
| 35 | + $maxCount = $wordCount[$word]; |
| 36 | + $mostCommonWord = $word; |
| 37 | + } |
| 38 | + |
| 39 | + } |
| 40 | + |
| 41 | + return $mostCommonWord; |
| 42 | + |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +$solution = new Solution(); |
| 47 | + |
| 48 | +$paragraph = "a, a, a, a, b,b,b,c, c"; |
| 49 | + |
| 50 | +$banned = ["a"]; |
| 51 | + |
| 52 | +$result = $solution->mostCommonWord($paragraph, $banned); |
| 53 | + |
| 54 | +print_r($result); |
0 commit comments