Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3987e89

Browse files
committed
819
1 parent 4f831db commit 3987e89

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /